dvilela
dvilela

Reputation: 1262

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?

Upvotes: 1

Views: 515

Answers (2)

Bathsheba
Bathsheba

Reputation: 234715

61183 in hexadecimal is 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. Hence the output of std::hex is not contingent on endianness, although it might be a factor in the internal calculations.

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

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.

Upvotes: 6

Related Questions