என்னைப் பற்றி

My photo
Bangalore, Karnataka, India

Friday, May 28, 2010

To print how a floating point number is stored in memory (C program).

The below C program would sweep through from 0.0 in steps of 0.1 and print how every number is stored in memory bitwise.

#include
//Power of union is used in this program
union a {
int i;
float f;
};

int main ()
{
float g = 0.0;
union a h;
unsigned int temp = 0x80000000; // Bitwise is 1 followed by 31 0's.
int temp1 = 0;
printf("%d is the size of structure\n", sizeof(union a));
while(1)
{
temp = 0x80000000;
h.f = g; // You cannot use bitwise operation on a floating
// point number so we assign the value to a float in a union
// having both int and float and do bit-wise on int.
printf("%d, %f, ", h.i, h.f);
while(temp)
{
temp1 = temp & h.i; // check if the bit is there or not.
printf("%d", temp1/temp); //We dont need the value at
// but if the value is there or not.. so this.
temp = temp >> 1; // Move the 1 to 1 position right.
}
printf("\n");
g += 0.1;
}
}

Comments for optimized code is welcome....

Ganesh Shanmugalingam

No comments: