Bytes to float

Started by
5 comments, last by Bimble Bob 13 years, 9 months ago
Quick question:

Why does

float test = (float)(floatBytes[3] << 24 | floatBytes[2] << 16 | floatBytes[1] << 8 | floatBytes[0]);


not produce the same result as

float test = *(reinterpret_cast<float *>(floatBytes))


The bottom example produces the expected result whereas the top produces a crazy high/low value that isn't what I wanted.
It's not a bug... it's a feature!
Advertisement
Quote:Original post by Dom_152
Quick question:

Why does

float test = (float)(floatBytes[3] << 24 | floatBytes[2] << 16 | floatBytes[1] << 8 | floatBytes[0]);


not produce the same result as

float test = *(reinterpret_cast<float *>(floatBytes))

Because that's not how floating-point numbers are represented internally. Read this if you have a lot of time in your hands, or perhaps this if you don't.

Think what does (float)1 do? It takes the value of 1 and converts it to the floating point value 1.0f. Now look at what the bit pattern that 1.0f is for a IEEE 754 single precision number:

0111 1111 0000 0000 0000 0000 0000 0000

Compare to the bit pattern for 1 as a 32-bit integer:

0000 0000 0000 0000 0000 0000 0000 0001
Yeah, that makes sense. So how would someone had gone about doing this in C, for example. reinterpret_cast doesn't exist in C so I'm curious how it's done.
It's not a bug... it's a feature!
Quote:Original post by Dom_152
Yeah, that makes sense. So how would someone had gone about doing this in C, for example. reinterpret_cast doesn't exist in C so I'm curious how it's done.


char bytes[4];

float *fp = (float*)bytes; //recast the byte pointer to a float pointer

float f = *fp; //dereference the float pointer

You can ofcourse dereference and recast without using a temporary variable by doing float f = *((float*)bytes);
[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!
Quote:Original post by Dom_152
Yeah, that makes sense. So how would someone had gone about doing this in C, for example. reinterpret_cast doesn't exist in C so I'm curious how it's done.


Like this:

float test = *((float *)floatBytes);


C cast is the same as reinterpret_cast when applied to most types.
Thanks a lot for the help!
It's not a bug... it's a feature!

This topic is closed to new replies.

Advertisement