Convert 4 bytes into a float

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.
You have to look up the IEEE floating point format.

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

hmm. seems like bit manipulation to me.. do you mean the four bytes you posted should make a float equivalent to 0.1?
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
@kbw
nice!
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?
hehe.. i am also amaze by that code.. what part don't you understand? so i can explain..
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. =[
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.