Reputation: 123
So, in C I am trying to give a floating point variable a number in binary bits (or hexadecimal digits) and then print it out, however it doesn't want to print the number I have calculated by hand or with an online converter.
float x = (float) 0b01000001110010000000000000000000;
or
float x = (float) 0x41C80000;
When printed out using
printf("%f", x);
produces results like this:
1103626240.000000
Instead of the expected 25, due to a sign bit of 0, exponent bit of 131, and a fraction of 1.5625.
Why is this, and how can I get the results I want?
Upvotes: 0
Views: 183
Reputation: 937
The value 0x41C80000
in hex, is an integer that has the value 1103626240
in decimal. In your code, you are casting this value to a float
which gives you this result:
x = 1103626240.000000
A solution for this can be made using a union
:
union uint_to_float {
unsigned int u;
float f;
};
union uint_to_float u2f;
u2f.u = 0x41C80000;
printf("x = %f\n", u2f.f);
EDIT:
As mentioned by @chux, using uint32_t
from stdint.h
, instead of unsigned int
is a better solution.
Upvotes: 3