Search code examples
c++hexbyteendianness

Does C++ std::hex reverse bytes order? (printing decimal as hexadecimal)


I'm having some trouble understanding the following C++ code:

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.

enter image description here

As you can see, I expected the output of the line of code to be FFEE instead of 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?


Solution

  • Endianness is about how to store numbers in byte-addressed memory.

    On the other hand, std::hex produces hexadecimal text.

    0x1000 * 14 + 0x100 * 14 + 0x10 * 15 + 0x1 * 15 == 61183, so 61183 is EEFF in hexadecimal.

    This won't be affected by endianness.