我试图在C中打印出浮点数的每一位.
我能够用这个整数做到这一点:
int bit_return(int a, int loc)
// Bit returned at location
{
int buf = a & 1<<loc;
if (buf == 0)
return 0;
else
return 1;
}
Run Code Online (Sandbox Code Playgroud)
如果我替换int a为编译器将无法编译float a.
这有解决方案吗?
复制并重新格式化您的评论如下
好的,对于不清楚的人,我在这里发布我的整个代码:
#include <stdio.h>
#include <stdlib.h>
int bit_return(int a, int loc) // Bit returned at location
{
int buf = a & 1<<loc;
if (buf == 0)
return 0;
else
return 1;
}
int main()
{
int a = 289642; // Represent 'a' in binary
int i = 0;
for (i = 31; i>=0; i--)
{
printf("%d",bit_return(a,i));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
感谢Pascal Cuoq的评论.我终于弄清楚如何解决自己的问题.是的,只需将浮点数的地址分配给指向整数的指针,然后取消引用它.这是我的代码解决方案:
#include <stdio.h>
// bit returned at location
int bit_return(int a, int loc)
{
int buf = a & 1<<loc;
if (buf == 0) return 0;
else return 1;
}
int main()
{
//11000010111011010100000000000000
// 1 sign bit | 8 exponent bit | 23 fraction bits
float a = -118.625;
int *b;
b = &a;
int i;
for (i = 31; i >= 0; i--)
{
printf("%d",bit_return(*b,i));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
将 float 的地址转换为相同大小的 int 地址,并将该 int 传递给现有函数。
| 归档时间: |
|
| 查看次数: |
11139 次 |
| 最近记录: |