so I got a task where I have to extract the sign, exponent and mantissa from a floating point number given as uint32_t. I have to do that in C and as you might expect, how do I do that ?
For the sign I would search for the MSB (Most Significant Bit, since it tells me whether my number is positive or negative, depending if it's 0 or 1)
Or let's get straight to my idea, can I "splice" my 32 bit number into three parts ?
Get the 1 bit for msb/sign Then after that follows 1 byte which stands for the exponent and at last 23 bits for the mantissa
It probably doesn't work like that but can you give me a hint/solution ? I know of freexp, but I want an alternative, where I learn a little more of C. Thank you.
If you know the bitwise layout of your floating point type (e.g. because your implementation supports IEEE floating point representations) then convert a pointer to your floating point variable (of type float
, double
, or long double
) into a pointer to unsigned char
. From there, treat the variable like an array of unsigned char
and use bitwise opertions to extract the parts you need.
Otherwise, do this;
#include <math.h>
int main()
{
double x = 4.25E12; /* value picked at random */
double significand;
int exponent;
int sign;
sign = (x >= 0) ? 1 : -1; /* deem 0 to be positive sign */
significand = frexp(x, &exponent);
}
The calculation of sign
in the above should be obvious.
significand
may be positive or negative, for non-zero x
. The absolute value of significand
is in the range [0.5,1)
which, when multiplied by 2
to the power of exponent
gives the original value.
If x
is 0
, both exponent
and significand
will be 0
.
This will work regardless of what floating point representations your compiler supports (assuming double
values).