Search code examples
chexunions

Why does this print only 0?


New to C, I've been trying to convert a hex input with this code. The input argv[1] I've been giving it is 0xabcd123. It has only given me 0 outputs. I have also tried using atoi as well as varying the types of outputs. Why does it only print 0? Here is the code, thanks

#include <stdio.h>
#include <stdlib.h>
typedef union{ 
    double num; 
    float f; 
} U;
int main(int argc, char*argv[])
{   

U u;
u.num = strtod(argv[1], NULL);
    printf("%e\n", u.f);
return 0;
}

result is platform dependent!


Solution

  • I believe its returning 0 on one system because of byte order. when you write to the value as a double but then read it as a float, you may be reading the top or bottom half of the double, depending on the architecture. on one system it's the empty top half of the double, on another its the bottom half which contains value.

    either way, with a union, you should never expect to write any value as one type, and read back as another and get reliable results. as you have discovered :) unions aren't magic type converters, they simply allow you to save space when you know you have one type of value at a time.