How to read the bits in a IEEE 754 number?

Posted by on mai 08, 2007
Fără categorie

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

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

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.

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.