双位数的位表示 [英] bit representation of a double number
问题描述
我做了这个程序,它的功能如预期,知道浮点的位表示:
I did this program, which functions as expected, to know the bit representation of a float:
float x1=-675.78125;
int *pint1;
pint1=(int *)&x1;
for(int i=0;i<8*sizeof(float);i++)
{
if(*pint1&1)
{
cout<<1;
}
else
cout<<0;
*pint1>>=1;
}
但它不适用于double: p>
But it doesn't work for a double:
double x=-675.78125;
int *pint;
pint=(int *)&x;
for(int i=0;i<8*sizeof(double);i++)
{
if(*pint&1)
{
cout<<1;
}
else
cout<<0;
*pint>>=1;
}
你能解释一下为什么会这样吗?你会怎么做呢?非常感谢您的帮助。
Could you explain me why this is so? how would you do it? Thank you so much for your help.
推荐答案
您的第一个程序似乎工作,而你的第二个不是对于你的特定硬件,一个float的大小和int一样,而一个int没有足够的空间用于 double
。
The reason that your first program seems to work and your second doesn't is that for your particular hardware, the size of a float is the same as int, while an int doesn't have enough room for all the bits in a double
.
但是你已经违反了严格的别名规则,所以如果你真的想打印浮点类型的位,正确的方法是转换为 unsigned char *
,然后遍历char的每个位,同时将指针递增到底层浮点类型的每个字节。另请注意,在big-vs-little endian,您的程序的结果可能会有所不同。
But you're already violating the strict aliasing rules, so if you really want to print the bits of a floating point type the right way to do it is to cast to unsigned char*
and then iterate over each bit of the char while incrementing the pointer over each byte of the underlying floating point type. Also note that on big-vs-little endian the results of your program may vary.
这篇关于双位数的位表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!