简体   繁体   中英

C++ floating point representation

I am trying to create a float from a hexadecimal representation I got from here . For the representation of 32.50002 , the site shows the IEEE 754 hexadecimal representation as 0x42020005 .

In my code, I have this: float f = 0x42020005; . However, when I print the value, I get 1.10E+9 instead of 32.50002 . Why is this?

I am using Microsoft Visual C++ 2010.

When you assign a value to a float variable via = , you don't assign its internal representation, you assign its value. 0x42020005 in decimal is 1107427333, and that's the value you are assigning.

The underlying representation of a float cannot be retrieved in a platform independent way. However, making some assumptions (namely, that the float is in fact using IEEE 754 format), we can trick a bit:

float f;
uint32_t rep = 0x42020005;
std::memcpy(&f, &rep, sizeof f);

Will give the desired result.

0x42020005 is an int with value of 1107427333.

float f = 0x42020005; is equal with float f = 1107427333;

0x42020005 actually is int value of 1107427333.

You can try out this code. Should work... Use union:

union IntFloat {
  uint32_t i;
  float f;
};

and call it when you need to convert the value.

union IntFloat val;
val.i = 0x42020005;
printf("%f\n", val.f);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM