cieee-754mantissa

Getting the mantissa (of a float) of either an unsigned int or a float (C)


So, i am trying to program a function which prints a given float number (n) in its (mantissa * 2^exponent) format. I was abled to get the sign and the exponent, but not the mantissa (whichever the number is, mantissa is always equal to 0.000000). What I have is:

unsigned int num = *(unsigned*)&n;
unsigned int m = num & 0x007fffff;
mantissa = *(float*)&m;

Any ideas of what the problem might be?


Solution

  • You are stripping off the bits of the exponent, leaving 0. An exponent of 0 is special, it means the number is denormalized and is quite small, at the very bottom of the range of representable numbers. I think you'd find if you looked closely that your result isn't quite exactly zero, just so small that you have trouble telling the difference.

    To get a reasonable number for the mantissa, you need to put an appropriate exponent back in. If you want a mantissa in the range of 1.0 to 2.0, you need an exponent of 0, but adding the bias means you really need an exponent of 127.

    unsigned int m = (num & 0x007fffff) | (127 << 23);
    mantissa = *(float*)&m;
    

    If you'd rather have a fully integer mantissa you need an exponent of 23, biased it becomes 150.

    unsigned int m = (num & 0x007fffff) | ((23+127) << 23);
    mantissa = *(float*)&m;