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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值