Reputation: 497
I recently wrote a block of code that takes as an input an 8 digit hexadecimal number from the user, transforms it into an integer and then converts it into a float. To go from integer to float I use the following:
int myInt;
float myFloat;
myFloat = *(float *)&myInt;
printf("%g", myFloat);
It works perfectly for small numbers. But when the user inputs hexadecimal numbers such as:
0x0000ffff
0x7eeeeeef
I get that myInt = -2147483648 and that myFloat = -0. I know that the number I get for myInt is the smallest possible number that can be stored in an int variable in C.
Because of this problem, the input range of my program is extremely limited. Does anyone have any advice on how I could expand the range of my code so that it could handle a number as big as:
0xffffffff
Thank you so much for any help you may give me!
Upvotes: 0
Views: 1541
Reputation: 901
Does anyone have any advice on how I could expand the range of my code so that it could handle a number as big as
0xffffffff
You can't store 0xffffffff in a 32-bit int
; the largest positive hex value you can store in a 32 bit int
is 0x7FFFFFFF or (2^31 -1) or 2147483647, but the negative range is -2^31 or -2147483648,
The ranges are due to obvious limitations in the number of bits available and the 2's complement system.
Use an unsigned int
if you want 0xffffffff.
Upvotes: 0
Reputation: 755026
The correct way to get the value transferred as accurately as float
will allow is:
float myFloat = myInt;
If you want better accuracy, use double
instead of float
.
What you're doing is trying to reinterpret the bit pattern for the int
as if it was a float
, which is not a good idea. There are hexadecimal floating-point constants and conversions available in C99 and later. (However, if that's what you are trying, your code in the question is correct — your problem appears to be in converting hex to integer.)
If you get -2147483648
from 0x0000FFFF (or from 0x7EEEFFFF), there is a bug in your conversion code. Fix that before doing anything else. How are you doing the hex to integer conversion? Using strtol()
is probably a good way (and sscanf()
and friends is also possible), but be careful about overflows.)
Upvotes: 2