Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 382
MetallicPriest Avatar asked Mar 28 '13 15:03

MetallicPriest


People also ask

How do you find the mantissa of a floating-point?

To make the calculations easy, the sign of the exponent is not shown, but instead excess 128 numbering system is used. Thus, to find the real exponent, we have to subtract 127 from the given exponent. For example, if the mantissa is “10000000,” the real value of the mantissa is 128 − 127 = 1.

What is exponent and mantissa in floating-point?

The mantissa represents the actual binary digits of the floating-point number. The power of two is represented by the exponent. The stored form of the exponent is an 8-bit value from 0 to 255.

How do you find the mantissa and exponent?

In decimal, very large numbers can be shown with a mantissa and an exponent. i.e. 0.12*10² Here the 0.12 is the mantissa and the 10² is the exponent. the mantissa holds the main digits and the exponents defines where the decimal point should be placed. The same technique can be used for binary numbers.

How are the signs for exponent in floating-point numbers represented?

However, the format for the computer is structurally similar, but hex digits are used with excess 7FH notation. Eight digits are used to represent a floating point number : two for the exponent and six for the mantissa.


1 Answers

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; } float_cast;  int main(void) {   float_cast d1 = { .f = 0.15625 };   printf("sign = %x\n", d1.parts.sign);   printf("exponent = %x\n", d1.parts.exponent);   printf("mantisa = %x\n", d1.parts.mantisa); } 

Example based on http://en.wikipedia.org/wiki/Single_precision

like image 144
eran Avatar answered Sep 19 '22 15:09

eran