简体   繁体   English

打印出浮子的内六角

[英]Printing out the Internal Hex of a float

So I thought that I could print the internal hex of a float like this: 所以我认为我可以像这样打印float的内部十六进制:

const auto foo = 13.0F;
const auto bar = reinterpret_cast<const unsigned char*>(&foo);

printf("0x%02hhX%02hhX%02hhX%02hhX\n", bar[0], bar[1], bar[2], bar[3]);

This outputs: 这输出:

0x00005041 0x00005041

But when I look at the debugger, the hex that it is reporting for foo is: 但是当我查看调试器时,它为foo报告的十六进制是:

0x003EF830 0x003EF830

Can someone help me understand why this didn't work and what I'd need to do to make it work? 有人可以帮助我理解为什么这不起作用以及我需要做些什么来使它工作?

The hex value for the floating point value 13.0f is: 浮点值13.0f的十六进制值为:

0x41500000

Confirmation: 确认:

Take 0x41500000 which is in binary: 取二进制的0x41500000

0100,0001,0101,0000,0000,0000,0000,0000

which split into 1 bit sign, 8 bit exponent and 23bit mantissa is: 分为1位符号,8位指数和23位尾数为:

0 : 10000010 : 10100000000000000000000

And we can interpret this using the standard floating evaluation of: 我们可以使用以下标准浮动评估来解释这个:

-1^sx 1.<mantissa> x 2^(exponent-127)

as

(-1)^0 x 1.101 x 2^(10000010-1111111)

which is 是的

1.101bx (10b)^11b

which is 是的

1.625 x 8

which is 是的

13.0f

Which means your output is correct (assuming a little endian format) 这意味着您的输出是正确的(假设有一点小端格式)

How you are reading it in the debugger is incorrect 如何在调试器中读取它是不正确的

You almost got it. 你几乎得到了它。 I'm not sure what the debugger is displaying but it's not your float. 我不确定调试器显示的是什么,但它不是你的浮动。 Maybe it's the address of it? 也许这是它的地址?

The actual float value is 0x41500000 . 实际浮点值为0x41500000 You can check it here: IEEE-754 Floating Point Converter . 你可以在这里查看: IEEE-754浮点转换器 If the link doesn't work you'll have to find the online floating point analyzer/description by yourself. 如果链接不起作用,您必须自己找到在线浮点分析仪/描述。

You did it the right way but you forgot that Intel x86 CPUs (I suppose that your CPU is Intel x86) are little endian . 你是以正确的方式做到的,但是你忘记了英特尔x86 CPU(我认为你的CPU是英特尔x86)是小端 That means that higher significance bytes are on higher memory addresses. 这意味着更高的重要字节位于更高的内存地址上。 So you should print out bytes in the reverse order than you're printing them, like this: 因此,您应该以与打印它们相反的顺序打印字节,如下所示:

printf("0x%02hhX%02hhX%02hhX%02hhX\n", bar[3], bar[2], bar[1], bar[0]);

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

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