Integer to 32-bit Float?
I know the very basics of C, however I'm having some trouble dealing with floats and converting values. I want my program to read a signed 16-bit integer and save the value as a 32-bit float in hexadecimal. Here is an example of what I need:
Input a value: 2000
32-bit float for this value equals 0x44FA0000
Input a value: -2000
32-bit float for this value equals C4FA0000
And also the opposite:
Input a float (in hex): 44FA0000
The decimal value for this is 2000.
So far my programs only did very simple operations, so I'm not sure how to deal with this. Can someone please shed some light or point to me some reference on what kind of functions/libs I need for this?
The details are here. You can probably do the first part with a simple assignment. The second will take a little more work (you have to know how to read in hex, and do some pointer casts).
scanf and the %x format specifier for printf for when you access the float through a char*.
OK, I tried this. Why does the second part work but the first doesn't?
printf( "Enter an decimal integer: " );
scanf( "%d", &i );
printf(" Value in float: %f\n", i);
printf( "Enter a hex 32-bit float: " );
scanf( "%x", &f );
printf( "Value in decimal: %f\n", f);
Well -- read your code. You read in an integer. You then re-interpret that integer's bit pattern as a floating point thing when you print it out. Why would you expect that to convert an integral value to the floating-point hex pattern that contains an equal value?
I think you should download one of the C draft standards in the sticky because some of these online references aren't really complete when it comes to format specifiers. For example, %x is for an unsigned int, not a float.
Well, I'm making an assumption, namely that sizeof(int)==sizeof(float)==4. If so, reading an integer that's supposed to represent a float hex-pattern and putting it in a float (part 2 above) works fine.
To do part 1, you need to convert values, which is done with =.
Actually he's got that part right. He reads in an integer into a 4 bit value that he later reinterprets as a float. The type of i and f have no bearing here, as long as they are 4 bytes. In fact, an array of 4 chars may be the best type since that's guaranteed to be 4 bytes.
Originally Posted by robwhit
The results are predictable, but not well defined. Unfortunately I don't see a well defined way of doing this in C (unlike C++).
BTW- why are you requiring the user to input an integer for part 1? Any decimal should be printable as a float. And that way you Part 1 is the exact inverse of part 2; just as in part 2 any hex sequence can be converted into a positive or negative decimal value, so would the inverse convert any positive or negative value to an IEEE floating point number.