# Bytes to float

This topic is 3042 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites
Quote:
 Original post by Dom_152Quick question:Why doesfloat test = (float)(floatBytes[3] << 24 | floatBytes[2] << 16 | floatBytes[1] << 8 | floatBytes[0]);not produce the same result asfloat test = *(reinterpret_cast(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.

##### Share on other sites
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

##### Share on other sites
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.

##### Share on other sites
Quote:
 Original post by Dom_152Yeah, 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);

##### Share on other sites
Quote:
 Original post by Dom_152Yeah, 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.

##### Share on other sites
Thanks a lot for the help!

1. 1
Rutin
33
2. 2
3. 3
4. 4
5. 5

• 13
• 9
• 9
• 9
• 9
• ### Forum Statistics

• Total Topics
633331
• Total Posts
3011390
• ### Who's Online (See full list)

There are no registered users currently online

×