Thursday, November 20, 2008

How C programming compiler stores float values ?

How does C compiler stores float values ?


Ans: In C, the float values are stored in a mantissa and exponent form. While writing a number we specify the exponent part in the form of base 10. But, in case of C compiler, the exponent for floats is stored in the form of base 2. 
Obviously, because, computer stores the numbers in binary form. 
The C compiler follows an IEEE standard to store a float. The IEEE format expresses a floating-point number in a binary form known as `normalized' form. Normalization involves adjusting the exponent so that the "binary point" (the binary analog of the decimal point) in the mantissa always lies to the right of most significant nonzero digit. In binary representation, this means that the most significant digit of the mantissa is always a 1. This property of the normalized representation is exploited by the IEEE format when storing the mantissa. Let us consider an example of generating the normalized form of a floating point number. Suppose we want to represent the decimal number 5.375. Its binary equivalent can be obtained as shown below:

2 | 5
.375 x 2 = 0.750 0
|------
.750 x 2 = 1.500 1
2 | 2 1
.500 x 2 = 1.000 1
|------
2 | 1 0
|------
| 0 1

Writing remainders in reverse writing whole parts in the same order we get 101 order in which they are obtained we get 011 thus the binary equivalent of 5.375 would be 101.011. The normalized form of this binary number is obtained by adjusting the exponent until the decimal point is to the right of most significant 1. In this case the result is 1.01011 x 22. The IEEE format for floating point storage uses a sign bit, a mantissa and an exponent for representing the power of 2. The sign bit denotes the sign of the number: a 0 represents a positive value and a 1 denotes a negative value. The mantissa is represented in binary. Converting the floating-point number to its normalized form results in a mantissa whose most significant digit is always 1. The IEEE format takes advantage of this by not storing this bit at all. The exponent is an integer stored in unsigned binary format after adding a positive integer bias. This ensures that the stored exponent is always positive. The value of the bias is 127 for floats and 1023 for doubles. Thus, 1.01011 x 22 is represented as shown below:

--- --------------- ----------------------------------------------
| 0 | 100 0000 1 | 010 1100 0000 0000 0000 0000 |
--- ---------------- ---------------------------------------------

sign bit exponent- mantissa stored in normalized form obtained after adding a bias
127 to exponent 2

No comments:

Blog List