bit representation of a double number

2019-03-05 00:03发布

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.

1条回答
一夜七次
2楼-- · 2019-03-05 00:51

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.

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.

查看更多
登录 后发表回答