简体   繁体   English

双数的位表示

[英]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;

}

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. 非常感谢你的帮助。

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 . 您的第一个程序似乎起作用而第二个程序似乎不起作用的原因是,对于您的特定硬件,float的大小与int相同,而int没有足够的空间容纳double所有位。

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. 但是您已经违反了严格的别名规则,因此,如果您真的想打印浮点类型的位,则正确的方法是将其转换为unsigned char* ,然后在递增char的同时迭代char的每一位指针指向基础浮点类型的每个字节。 Also note that on big-vs-little endian the results of your program may vary. 另请注意,在big-vs-little endian上,程序的结果可能有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM