Tuesday, 22 July 2014

Representation of Floating Point numbers

Code:
#include <iostream>
using namespace std;

void print_binary_representation(unsigned int x)
{
    size_t siz = 8*sizeof(x);    // sizeof returns size in bytes.
    for (size_t i = siz; i>0; i--)
    {
        int val = (((x >> (i-1)) << (siz-1)) >> (siz-1));
        cout << val;
        if ( i == 32 || i == 24)
            cout << ",";
    }
    cout << endl;
}


int main()
{
    float x = 2.0;
   
    cout << "Size of float: " << sizeof(float) << endl;
    cout << "Size of unsigned int: " << sizeof(unsigned int) << endl;

    do
    {
        void *vx = &x;
        unsigned int xui = *(unsigned int*)vx;
        unsigned int xui_direct = (unsigned int)x;
        cout << "Representation of " << x << " as unsigned int: " << xui << ", binary: ";
        print_binary_representation(xui);
        cout << "Enter number: ";
        cin >> x;
    }while( x != 1234);
   
    return 0;
}

Output:
Size of float: 4
Size of unsigned int: 4
Representation of 2 as unsigned int: 1073741824, binary: 0,10000000,00000000000000000000000
Enter number: -4
Representation of -4 as unsigned int: 3229614080, binary: 1,10000001,00000000000000000000000
Enter number: 8
Representation of 8 as unsigned int: 1090519040, binary: 0,10000010,00000000000000000000000
Enter number: -8
Representation of -8 as unsigned int: 3238002688, binary: 1,10000010,00000000000000000000000
Enter number: 123456
Representation of 123456 as unsigned int: 1206984704, binary: 0,10001111,11100010010000000000000
Enter number: -123456
Representation of -123456 as unsigned int: 3354468352, binary: 1,10001111,11100010010000000000000
Enter number: 1234

Using Visual Studio 2012 64-bit Compiler.

NumberSignExponentFractionExp-valexpected expansion of fraction
40100000010000000000000000000000021
-41100000010000000000000000000000021
80100000100000000000000000000000031
-81100000100000000000000000000000031
12345601000111111100010010000000000000161.883789063
-12345611000111111100010010000000000000161.883789063
2.760100000000110000101000111101011111.38
In the above table, the Sign-Exponent-Fraction columns form the binary representation of "Number" in a float type.
Note that in "expected expansion of fraction" column, all numbers start are of the form 1.*. So while storing the fraction portion this 1 is omitted and Fraction expands only to the part after decimal point. For e.g. 01100001010001111010111 evaluates to 0.38
example of decimal to binary fraction conversion:

0.380.760
0.761.521
0.521.041
0.040.080
0.080.160
0.160.320
0.320.640
0.641.281
0.280.560
0.561.121
0.120.240
0.240.480
0.480.960
0.961.921
0.921.841
0.841.681
0.681.361
0.360.720
0.721.441
0.440.880
0.881.761
0.761.521
Thus giving 0110000101000111101011.
Note that the pattern would repeat itself since the last row and second row match.

No comments: