• Advertisement
Sign in to follow this  

Bytes to float

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
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);

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement