Goose
Goose

Reputation: 2250

Normalizing Binary Floating Point Values

If you have something like the floating-point binary value 1101.101, it is normalized as 1.101101 x 2^3 by moving the decimal point 3 positions to the left.

I don't know how to do this in code.

So if I have 10010000 exp 0 and I want to get 01001000 exp 1, the fraction field is "001" and the final result is 010001.

If I have an 8 bit number and the leading 2 bits are 00, I want to move it until I find a 1, or if I have a leading bit of 01 then it is already normalized. Similary for a leading 2 bits of 11 I move it to the left one.

So if my number was 32 bits, 1 for the sign, 8 for the exponent, 23 for the mantissa, I do something like:

if ( (result >> 24) == "11") ) // although here I know I'm comparing an int with a string
   {
   //code to set result = to the new number
   }
if ( (result >> 24) == "01" ) )
   {
      return result; 
   }

And then several more if statements for the other 2 leading bit numbers (00, 10)?

What is wrong with my logic/code?

Upvotes: 1

Views: 8406

Answers (2)

DevGoldm
DevGoldm

Reputation: 828

IEEE 754 single precision format


Like you say, you need to extract the sign, mantissa and exponent. The diagram above taken from Wikipedia shows how it is laid out for the most common single precision floating point format, IEEE 754.

To extract each part we need to do this in three steps detailed below. I don't have the C code but I will show the steps you need to take. After extracting the 3 parts just place them in the bit positions shown in the diagram above.

1. Sign

If it's an unsigned number this is always 0.

If it's signed it's the MSB.

2. Exponent

If the number is signed and negative you will need to flip all the bits and add 1 to turn it positive. If not you can leave it as it is.

To extract the exponent we must know where the binary point is meant to be. Let the position of the binary point be b (In your example its 3).

Let the first bit from the MSB that is 1 be p (In your example its 6).

Letting the exponent be e:

e = 127 - (b - p)

3. Mantissa

This will be equal to the bits from position p-1 down to bit 0.

Upvotes: 1

0xF1
0xF1

Reputation: 6116

No it is not correct.

The floating point numbers are represented in IEEE 754 Floating point format, you cannot just shift the number to normalize it.

If you want to represent the number in this format:

(+/-)1.M x 2E

Then you will have to extract sign bit, mantissa M and exponent E separately first.

Then do binary operations (shifting, AND, OR, etc.) to represent it in the way you want.

Upvotes: 1

Related Questions