Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Binary representation of float number in memory in C (http://www.go4expert.com/forums/binary-representation-float-memory-c-t26653/)

stefanvozd 9Sep2011 18:59

Binary representation of float number in memory in C
 
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 10Sep2011 02:48

Re: Binary representation of float number in memory in C
 
Needs more work - the output is wrong. 3.14 to 32 significant binary digits is 11.001000111101011100001010001111

stefanvozd 10Sep2011 04:12

Re: Binary representation of float number in memory in C
 
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 10Sep2011 04:14

Re: Binary representation of float number in memory in C
 
cant edit post or paste links... copy without vvv

xpi0t0s 10Sep2011 04:15

Re: Binary representation of float number in memory in C
 
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 10Sep2011 04:32

Re: Binary representation of float number in memory in C
 
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.


All times are GMT +5.5. The time now is 15:48.