Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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);

0x42020005 is an int with value of 1107427333.

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top