Binary representation of float number in memory in C

Newbie Member
9Sep2011,18:59   #1
stefanvozd's Avatar
Hi this is my first post.
I whona share my function that i have write in C , for Binary representation of float number in memory.


Code:
void float_to_bin(float f){
	long unsigned x;
	int i=0;
	unsigned int mmask;

	x = *(long*)&f;

	mask = 1<<(sizeof(x) * 8 - 1);

	while (mask > 0) 
	{
		if(i==1) printf (" ");
		if(i==7) printf (" ");
		i++;

		if (x & mask)
			printf("1");
		else
			printf("0");
		mask >>= 1;
	}
}
All you need to do is pass a float number to function and you il have binary representation of float number in memory.

Example: I you pass number 3,14. You will get on screen: 0 100000 0010010001111010111000011
Mentor
10Sep2011,02:48   #2
xpi0t0s's Avatar
Needs more work - the output is wrong. 3.14 to 32 significant binary digits is 11.001000111101011100001010001111
Newbie Member
10Sep2011,04:12   #3
stefanvozd's Avatar
this is representation of float in memory
you can chek it here to

vvv.h-schmidt.net/FloatApplet/IEEE754.html
same result as in mu function


dont know how you get 11.001000111101011100001010001111
Newbie Member
10Sep2011,04:14   #4
stefanvozd's Avatar
cant edit post or paste links... copy without vvv
Mentor
10Sep2011,04:15   #5
xpi0t0s's Avatar
11 is 3, . is the binary point, 0010001 etc is 0.14. This is 3.14 in binary.

Of course, if you're just doing a binary memory dump of the float representation of 3.14 then the output could well be correct. But it's not a lot of use.
Newbie Member
10Sep2011,04:32   #6
stefanvozd's Avatar
output is based on IEEE standard for representation of float number in memory.
it shows how float is it stored in memory.

you are right, cant have much of use in programing, it is mainly for education.