Convert 4 bytes into a float

Jan 23, 2010 at 1:48am
I've being trying to convert 4 bytes into a float with no success.

Float:
0.1

The bytes are:
1: 205
2: 204
3: 204
4: 61

A formula for doing so would be great, I have to do this without declaring any float values, purely the formula which will result in the float.

I do not think posting my attempts will benefit this topic, I really have no idea how to do this, It seems extremely complicated all this mantissa kind of stuff.
Jan 23, 2010 at 2:24am
You have to look up the IEEE floating point format.

You can get it here:
http://babbage.cs.qc.edu/IEEE-754/Decimal.html

Jan 23, 2010 at 2:25am
hmm. seems like bit manipulation to me.. do you mean the four bytes you posted should make a float equivalent to 0.1?
Jan 23, 2010 at 2:38am
I have no idea why you are dong this, but I hope this code helps you understand what's going on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

union UStuff
{
        float   f;
        unsigned char   c[0];
};

int main()
{
        UStuff a, b;
        a.f = 0.1;

        for (size_t i = 0; i < sizeof(UStuff); ++i)
        {
                std::cout << "byte " << i << ": "
                        << (unsigned int)(a.c[i])
                        << std::endl;

                b.c[i] = a.c[i];
        }
        std::cout << b.f << std::endl;

        return 0;
}


Output (intel mac):
1
2
3
4
5
byte 0: 205
byte 1: 204
byte 2: 204
byte 3: 61
0.1

Last edited on Jan 23, 2010 at 2:39am
Jan 23, 2010 at 2:45am
@kbw
nice!
Jan 23, 2010 at 11:19am
Ooo, this looks good.

Having abit of trouble trying to decode this code with 1 letter vars. Hard to tell what is going on. =\ Maybe comments?
Jan 23, 2010 at 11:25am
hehe.. i am also amaze by that code.. what part don't you understand? so i can explain..
Jan 25, 2010 at 9:03pm
I'm just not sure what each line is used for.
1
2
3
4
5
union UStuff
{
        float   f;
        unsigned char   c[0];
};

I've not seen union before, this looks abit like a struct. Is there any difference between the two?
I do not see what sort of purpose initilizing 1 cell for variable c would have? why not just c without the 1 cell array? Same thing I think.

size_t i = 0
Why would you use size_t? Would it give the "i" a data type suitable for holding the bytesize for sata structure UStuff?

1
2
3
4
5
std::cout << "byte " << i << ": "
<< (unsigned int)(a.c[i])
<< std::endl;

b.c[i] = a.c[i];

These one letter variables are confusing me, I cannot tell what they are for. =[
Jan 25, 2010 at 9:36pm
Jan 25, 2010 at 11:13pm
Where did the problem from in the first place. If you can't understand the code, you'll have to explain where the question came from.
Topic archived. No new replies allowed.