问题
I am trying to figure out the algorithm to this but all I get with google is doing it with casting. I need to know the details.
So if we have a float x and want to return its binary representation what do we need to do?
I know we need to return the float if its NaN or a infinity but otherwise what are the steps?
EDIT
The function takes in an unsigned int, to be used as if it was a float, and then return the integer the number represents. I cannot use casting, just conditionals and bit-wise operators.
回答1:
Alternatively, use a union:
typedef union
{
float f_;
int i_;
} FloatBits;
FloatBits fb;
fb.f_ = 1.5;
Then fb.i_
contains the float mapped onto an int
to allow extraction of the bits. Again, usual assunptions about the size of types - you can verify these using sizeof
.
Using this approach, you can play with setting the bits in fb.i_
directly and seeing them mapped back into the float
.
回答2:
To test if a 32-bit value represents NaN if it were a float you can check if its unsigned value is greater than the representation for infinity.
int n =
if((n & 0x7FFFFFFF) > 0x7f800000) // is NaN
Removing the sign is required as a NaN can have negative sign bit set to 1 (though NaN is not positive or negative)
If you want to know if a float is NAN, you can use
float f = NAN
if (f != f) // is NAN
To compare with Infinity
float f = INFINITY;
if (f == INFINITY)
回答3:
The float
number in c
programming language follows the IEEE Standard for Floating-Point Arithmetic (IEEE 754).
You can convert float
to int
with the code
int i = *(int *)&f; // f is the float variable you want to convert
And then interpret the int
yourself according to IEEE 754 standard.
来源:https://stackoverflow.com/questions/7396591/bitwise-float-to-int