1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Binary representation of float number in memory in C

Discussion in 'C' started by stefanvozd, Sep 9, 2011.

  1. stefanvozd

    stefanvozd New Member

    Joined:
    Sep 9, 2011
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Needs more work - the output is wrong. 3.14 to 32 significant binary digits is 11.001000111101011100001010001111
     
  3. stefanvozd

    stefanvozd New Member

    Joined:
    Sep 9, 2011
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  4. stefanvozd

    stefanvozd New Member

    Joined:
    Sep 9, 2011
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    cant edit post or paste links... copy without vvv
     
  5. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    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.
     
  6. stefanvozd

    stefanvozd New Member

    Joined:
    Sep 9, 2011
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    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.
     

Share This Page