Union read/write in C
I'm having some difficulty understanding why the output of the following code is not what I expect. In the first loop iteration all values print correctly, however in all subsequent iterations the output 开发者_运维问答of fi_union.float_val is 0.
I'm using the union to essentially replace pointer aliasing, and be able to interpret the 64 bits as an uint64_t or an IEEE 754 double precision value. Is this the proper way to go about this?
I know bit shifting a IEEE 754 value will result in garbage essentially. As odd as it sounds, that's what I'm going for. I really would like to know why fi_union.float_val is zero after the first iteration. I don't have any GCC optimizations turned on.
I'm using gcc version 4.4.3 on an x86_64 architecture.
double v1 = 0xDE.62133p0;
union float_interpret
{
uint64_t val;
double float_val;
} fi_union;
for( int i = 0; i <= 35; i++ )
{
fi_union.val = *(uint64_t*)(&v1) >> i;
printf( "\n %f >> %*i = %16lX \t %20li \t %15f", v1, 2, i, fi_union.val, fi_union.val, fi_union.float_val );
}
Floating-point variables, according to IEEE 754, are composite data structures with three or four components: sign, exponent, mantissa and optionally a quiet NaN flag (embedded in the mantissa). Shifting the whole memory representation like you did in fi_union.val = *(uint64_t*)(&v1) >> i;
will not return anything meaningful.
So the expected results are indeed what you see, on the first iteration, when i = 0, no shifting is performed and the value returned is ok. When you start shifting bits in the memory representation of the float, you are trowing the sign bit over the exponent, the exponent bits over the mantissa, etc. This causes a mess.
If you want to inspect the contents of the memory representation of the floating-point number, use <ieee754.h>
from glibc.
Something like this (not tested):
#include <ieee754.h>
...
union ieee754_double x;
x.d = v1
printf("sign: %u; mantissa: %llu; exponent: %u\n",
(unsigned) x.ieee.negative,
((unsigned long long) x.ieee.mantissa1 << 20) | ((unsigned long long) x.ieee.mantissa0),
(unsigned) x.ieee.exponent - IEEE754_DOUBLE_BIAS);
You say the first time through the loop, it works as you expect, but not the later iterations. I don't have a gcc compiler in front of me, so I can't test this, but would this work for you?
fi_union.float_val = v1;
for( int i = 0; i <= 35; i++ )
{
printf( "\n %f >> %*i = %16lX \t %20li \t %15f", v1, 2, i, fi_union.val, fi_union.val, fi_union.float_val );
fi_union.val = fi_union.val >> 1;
}
Looking at the operator precedence rules, your assignment to fi_union.val
should work, but I'm guessing that's what's not working when i > 0
. Therefore, try to bypass it by using the union to replace the pointer aliasing.
精彩评论