MetallicPriest MetallicPriest - 9 months ago 82
C Question

How to get the sign, mantissa and exponent of a floating point number

I have a program, which is running on two processors, one of which does not have floating point support. So, I need to perform floating point calculations using fixed point in that processor. For that purpose, I will be using a floating point emulation library.

I need to first extract the signs, mantissas and exponents of floating point numbers on the processor which do support floating point. So, my question is how can I get the sign, mantissa and exponent of a single precision floating point number.

Following the format from this figure,

enter image description here
That is what I've done so far, but except sign, neither mantissa and exponent are correct. I think, I'm missing something.

void getSME( int& s, int& m, int& e, float number )
unsigned int* ptr = (unsigned int*)&number;

s = *ptr >> 31;
e = *ptr & 0x7f800000;
e >>= 23;
m = *ptr & 0x007fffff;


I think it is better to use unions to do the casts, it is clearer.

#include <stdio.h>
typedef union {
  float f;
  struct {
    unsigned int mantisa : 23;
    unsigned int exponent : 8;
    unsigned int sign : 1;
  } parts;
} double_cast;

int main() {
  double_cast d1;
  d1.f = 0.15625;
  printf("sign = %x\n",;
  printf("exponent = %x\n",;
  printf("mantisa = %x\n",;
  return 0;

Example based on