简体   繁体   English

为什么我的浮点值不能正确打印?

[英]Why Isn't My Floating Point Values Printing Properly?

I am trying to print out the floating point values 0x40a00000 and 0xc0200000. 我正在尝试打印浮点值0x40a00000和0xc0200000。 But the values that I print out and the correct values according to the IEEE-754 Floating Point Converter ( https://www.h-schmidt.net/FloatConverter/IEEE754.html ) are completely different: 但是,根据IEEE-754浮点转换器( https://www.h-schmidt.net/FloatConverter/IEEE754.html ),我打印出的值和正确值完全不同:

The values I should get according to the IEEE converter: 我应该根据IEEE转换器获得的值:

0x3F800000 = 5.00
0xBF000000 = -2.50

The values I get when running: 我在运行时得到的值:

float tmp1 = 0x40a00000;
float tmp2 = 0xc0200000;

printf("tmp1 = %.2f\n", tmp1);
printf("tmp2 = %.2f\n", tmp2);

is

tmp1 = 1084227584.00
tmp2 = 3223322624.00

For some reason my C code isn't formatting the bits of the floating point values according to IEEE standards and is instead formatting them as if it were an int with a decimal point 由于某种原因,我的C代码没有按照IEEE标准格式化浮点值的位,而是将它们格式化为好像是带小数点的int

These are assigning the float representation of the hexadecimal numbers to the floats. 这些将十六进制数字的浮点数表示形式分配给浮点数。

Instead, do this: 相反,请执行以下操作:

int i1 = 0x40a00000;
int i2 = 0xc0200000;
float tmp1, tmp2;
memcpy(&tmp1, &i1, sizeof(int));
memcpy(&tmp2, &i2, sizeof(int));

Print them: 打印它们:

printf("tmp1 = %.2f\n", tmp1);
printf("tmp2 = %.2f\n", tmp2);

Output: 输出:

tmp1 = 5.00 tmp1 = 5.00
tmp2 = -2.50 tmp2 = -2.50

Full example: 完整示例:

#include <stdio.h>
#include <string.h>

int main(void)
{
    int i1 = 0x40a00000;
    int i2 = 0xc0200000;
    float tmp1, tmp2;
    memcpy(&tmp1, &i1, sizeof(int));
    memcpy(&tmp2, &i2, sizeof(int));
    printf("tmp1 = %.2f\n", tmp1);
    printf("tmp2 = %.2f\n", tmp2);
}

These aren't doing what you think they do: 这些没有按照您认为的去做:

float tmp1 = 0x40a00000;
float tmp2 = 0xc0200000;

You are simply using the hexadecimal representation of the decimal integers that are getting printed; 您只需使用要打印的十进制整数的十六进制表示形式即可; they do not shove these bytes in so they can be interpreted as floats. 它们不会将这些字节推入,因此可以将它们解释为浮点数。

It sounds like what you want to do is (somehow) get the bytes you want somewhere, get the address of that, and cast it to be a pointer to a float, which when dereferenced will be interpreted as a float. 听起来您想要做的是(以某种方式)在某个地方获取想要的字节,获取其地址,并将其强制转换为指向浮点数的指针,在取消引用时将其解释为浮点数。

union
{
   int i;
   float f;
}k1,k2;

k1.i = 0x40a00000;
k2.i = 0xc0200000;

printf("f1 = %.2f\n", k1.f);
printf("f2 = %.2f\n", k2.f);
int i1 = 0x40a00000;
int i2 = 0xc0200000;

float f1 = *(float*)&i1;
float f2 = *(float*)&i2;

printf("f1 = %.2f\n", f1);
printf("f2 = %.2f\n", f2);

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

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