سؤال

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!

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

num is declared as int. So printf("%d", u.num) or double num

  • First, please kindly reformat your code so that everyone can read it easily.
  • Second, the type of your u.num is double, so utilize %f or %lf instead of %d
  • Third, as shown in this codepad http://codepad.org/JSSJEKOn, your code is correct and it must obviously print the expected result. So I think that the error is not here but somewhere else in your source file. Please give us more information
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top