[英]Does C++ std::hex reverse bytes order? (printing decimal as hexadecimal)
I'm having some trouble understanding the following C++ code:我在理解以下 C++ 代码时遇到了一些麻烦:
std::cout << std::hex << 61183 << std::endl; // prints eeff
I'm working on a little-endian machine (Intel x86-64), and I wanted to understand, at bit and byte level, how that result is produced, so I wrote the following table for a least significant bit architecture.我正在使用 little-endian 机器(Intel x86-64),我想在位和字节级别了解该结果是如何产生的,因此我为最低有效位架构编写了下表。
As you can see, I expected the output of the line of code to be FFEE
instead of EEFF
.如您所见,我预计代码行的 output 是FFEE
而不是EEFF
。 So I must have missed something while making that table, but I don't really see what.所以我在制作那张桌子时一定错过了一些东西,但我真的不明白是什么。 Is std::hex
affected by the endianness of a computer? std::hex
是否受计算机字节序的影响?
Endianness is about how to store numbers in byte-addressed memory.字节序是关于如何在字节寻址的 memory 中存储数字。
On the other hand, std::hex
produces hexadecimal text.另一方面, std::hex
产生十六进制文本。
0x1000 * 14 + 0x100 * 14 + 0x10 * 15 + 0x1 * 15 == 61183
, so 61183
is EEFF
in hexadecimal. 0x1000 * 14 + 0x100 * 14 + 0x10 * 15 + 0x1 * 15 == 61183
,所以61183
是十六进制的EEFF
。
This won't be affected by endianness.这不会受到字节序的影响。
61183
in hexadecimal is EEFF
.十六进制的61183
是EEFF
。
Endianness is all to do with how some number values are stored in memory, not how conversions from one radix to another should be defined.字节序与一些数值如何存储在 memory 中有关,而不是如何定义从一个基数到另一个基数的转换。 Hence the output of std::hex
is not contingent on endianness, although it might be a factor in the internal calculations.因此, std::hex
的 output 不取决于字节顺序,尽管它可能是内部计算中的一个因素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.