8th
MAY

How to read the bits in a IEEE 754 number?

Posted by Strainu | Filed under C

That’s one of those questions you always wanted to know the answer to, but never found somebody who knew, right? :P

Well, in C it’s pretty simple. All you have to do is to declare an union, like this:

union{
float f;
int bits;
}

This tells the compiler that both f and bits should be hold in the same memory zone. This is pretty useful to save some memory, if you know for sure that you wown’t need f and bits in the same time.

As a side effect, if you write a value in f then read bits, you will have all the bits represented in the IEEE 754 standard. Now you can use bit operations (& , | , ^) with your number, you can extract the different parts of the number, etc. Do keep in mind that this is bad programming practice.

Share and Enjoy:
  • Facebook
  • Twitter
  • Identi.ca
  • email
  • Add to favorites
  • Digg
  • StumbleUpon

Tags: ,

Leave a Reply