Float and int members in a union does not show values

nikhil chaubey Source

I am trying to understand union and here is a example code I wrote,

#include <stdio.h>

union god{
    int body;
    float spirit;

union god human;

int main(void)
    float malice = 5.4;
    human.spirit = malice;
    printf("%ld %ld\n", sizeof(float), sizeof(int));
    printf("%d %f\n", human.body, human.spirit);
    return 0;

I expected 5 5.4 as output, because same memory is used for int and float types, I should be able to store both in same place.

However printing those values doesn't show my guess.

4 4
1085066445 5.400000

Output does not show both values as 5 5.4.

int and float both have same size, so same memory is used for holding them.

1.But why the output is like this?

2.Am I missing some float, union, printf related basics?



answered 6 days ago liliscent #1

For most of the implementation, int and float use essentially different representation in terms of bit. If you interpret the same bit sequence in float as int, the result is meaningless. You can't expect a float representation of 5.4 is also a int representation of 5.

See here some typical implementation of floating point, and here a typical representation of int.

answered 6 days ago Eric Postpischil #2

The value in a float is stored in a special format. In the most common format, it is encoded with one bit for a sign, eight bits for an exponent, and 23 bits for the significand (a fraction). For 5.4, the sign bit is 0 (for positive), the exponent is 2 and is encoded as 129 (127 is added; the exponent is stored with a bias), and the fraction is 1.35000002384185791015625, using the bits 0x2ccccd. (Those are the fraction minus one, then multiplied by 223.) Put together, the sign bit, the exponent bits, and the significand bits form 0x40accccd. In decimal, that is 1085066445.

So, when you store 5.4 in the float member of the union, the bits 0x40accccd are written to the storage. When you read the int member, those bits are interpreted as 1085066445.

comments powered by Disqus