I want convert the storage of a floating point number to an integer (the ‘number’ value is not required to be equal).
If a floating point number (eg 10), is represented in binary (at least on my implementation) as:
01000001001000000000000000000000
Then it should (also on my implementation) represent the integer value 1092616192.
I am currently doing this through the following:
union UNFI {
float a;
int b;
};
UNFI n;
n.a = 10;
int bits = n.b; // foo!
for (int i=31; i>=0; --i) {
bool bit = ((bits >> i) & 1);
std::cout << bit;
}
Which is achieving what I would like, but it is, in its nature, undefined behavior. Therefore I would like to know what the ‘correct’ way of achieving this outcome is.
From the C99 standard:
With one exception, if the value of a member of a union object is used when the most recent store to the object was to a different member,the behavior is implementation-defined.
Is that not undefined behavior?
The correct way is to call
memcpy. Most compilers will optimize this to an efficient single-word memory access just like the union, but on platforms with extra alignment requirements, they will do the right thing. And it won’t ever trigger a signalling NaN.or