Binary representation of float number in memory in C

stefanvozd's Avatar, Join Date: Sep 2011
Newbie Member
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
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Needs more work - the output is wrong. 3.14 to 32 significant binary digits is 11.001000111101011100001010001111
stefanvozd's Avatar, Join Date: Sep 2011
Newbie Member
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
stefanvozd's Avatar, Join Date: Sep 2011
Newbie Member
cant edit post or paste links... copy without vvv
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.
stefanvozd's Avatar, Join Date: Sep 2011
Newbie Member
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.