Print the bit pattern of a float

We can use bit shifting and bit-and operator to print out the bit pattern of an integer(a short, an int, a long, or even a char) easily. But how can we print out the bit pattern of a floating number(a float or a double)? In ANSI C standard, the operands of the bit operators cannot be a floating number. Then how can we solve this problem? Yep, the union type is needed. Below is the codes:

#include <stdio.h>

union zero
{
    
float f;
    
long l;
}
;

void printBitPattern(long x)
{
    
int i;
    
for(i = 31; i >= 0; i--)
    
{
        printf(
"%ld",(x>>i)&0x00000001);
    }

}


main()
{
    union zero z;

    z.f 
= 0.0;
    printBitPattern(z.l);
    printf(
" ");
    printBitPattern(
0L);

    printf(
" ");

    getch();
    
return 0;
}

In win-tc, the size of int is 2 bytes, for float is 4 bytes. So here a long type is used in the union. You can change it to an int type as long as the size of int in your environment is 4 bytes.

If you run it, the result will be two lines, each contains 32 zeros. So we come to the conclusion: a float zero has the same bit values as an int zero.

If you assign -0.0 to z.f, the first bit of the float pattern will be 1, others remain the same.

Okay, I have to stop here, because when I had done some more trials, I found floating number was not as easy as I expected first. And I am sure if you try some more, you will have the same feeling as I do. I will continue to learn more things about floating number and get a deeper understanding. Talk to you later.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章