简体   繁体   English

C ++浮点表示

[英]C++ floating point representation

I am trying to create a float from a hexadecimal representation I got from here . 我试图从我从这里得到的十六进制表示形式创建一个float For the representation of 32.50002 , the site shows the IEEE 754 hexadecimal representation as 0x42020005 . 对于32.50002的表示32.50002 ,该站点将IEEE 754十六进制表示形式表示为0x42020005

In my code, I have this: float f = 0x42020005; 在我的代码中,我有: float f = 0x42020005; . However, when I print the value, I get 1.10E+9 instead of 32.50002 . 但是,当我打印该值时,得到的是1.10E+9而不是32.50002 Why is this? 为什么是这样?

I am using Microsoft Visual C++ 2010. 我正在使用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. 当通过=float变量分配值时,不分配其内部表示,而是分配其值。 0x42020005 in decimal is 1107427333, and that's the value you are assigning. 十进制的0x42020005是1107427333,这就是您要分配的值。

The underlying representation of a float cannot be retrieved in a platform independent way. float的基础表示无法以独立于平台的方式进行检索。 However, making some assumptions (namely, that the float is in fact using IEEE 754 format), we can trick a bit: 但是,做一些假设(即, float实际上是使用IEEE 754格式的),我们可以欺骗一下:

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. 0x42020005是一个int ,其值是1107427333。

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

0x42020005 actually is int value of 1107427333. 0x42020005实际上是0x42020005int值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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