bit representation of floats, help please!!

Hi. Im new here and this is my first post, I hope you can help me with this problem I have: I'm trying to understand how the machine is working with different types of data (char, int, float, double, etc). So I made a program to see the bit representation for char and integers by using the bitwise operators. For example this is my function to see the binary representation of an integer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void binary(int integer )
{

    int bits =8*sizeof(int);
    unsigned mask=1<<(bits-1); 

    for(int i=1;i<=bits;i++)
    {
                if(mask & integer)

                    {
                        cout<<"1";

                    }
                        else cout<<"0";

                        if(i%4==0)
                            cout<<" ";

            mask=mask>>1;

        }

    }

Now my problem is that it doesn't work for floats or doubles, (I try to change the type of data received by the funcion but it doesnt work, I don't know why. I'm I doing something wrong?). Any idea about how can I make a function to see the bit representation of kind double or float? Thanks so much for your help.


Last edited on
you can use a 'void' pointer so the data can be read as byte:
1
2
3
4
5
6
7
8
9
10
void FloatBits(float value,char bits[33]){
    void *bytes=(void*)&value;
    int *temp=(int*)bytes;
    bits[32]='\0';
    for(int i=31;i>=0;i--){
        if(*temp & 1) bits[i]='1';
        else bits[i]='0';
        *temp >>=1;
    }
}

for 'double' is the same, the difference is that double has 64 bits. However, you should know the floating-point specifics of the IEEE754 for the floating-point number rappresentation:
http://en.wikipedia.org/wiki/IEEE_754-2008
Last edited on
Thanks so much for your help!!!
Topic archived. No new replies allowed.