1

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.

Kaseop
  • 29
  • 1
  • 5

1 Answers1

3

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).

Peter
  • 35,646
  • 4
  • 32
  • 74
  • For the first part, do you mean if you have `float x`, and `float* p_x = (float*) &x`.. how do you convert it to pointer to `unsigned char`? Like this : `unsigned char* ucp_x = (unsigned char*) p_x`? – galois Dec 21 '15 at 23:33
  • Then how would you access it "like an array"? – galois Dec 23 '15 at 00:35
  • If you need to ask that, you don't understand the relationship between arrays and pointers. Any basic C text book describes that. – Peter Dec 23 '15 at 02:09
  • I know how to index an array/pointer, but I'm asking how casting it to `unsigned char' gives you the representation in that form, and which indices represent what. – galois Dec 23 '15 at 07:14
  • Casting to an `unsigned char *` allows treating the memory occupied by the floating point variable like an array (of `sizeof float` characters in your example). As to what the individual characters mean, note the opening words of my answer "If you know the bitwise layout of your floating point type ...." – Peter Dec 23 '15 at 07:24