user2442944
user2442944

Reputation:

Inconsistent results when dealing with endianness and arrays in C++

I'm wondering why — in my sample code — when converting a reference to the first element of m_arr to a pointer of bigger size the program reads the memory to m_val in little-endian byte order? With this way of thinking *(std::uint8_t*)m_arr should point to 0x38, but it doesn't.

My CPU uses little-endian byte order.

#include <iostream>
#include <iomanip>

int main() {
    std::uint8_t m_arr[2] = { 0x5a, 0x38 };

    // explain why m_val is 0x385a and not 0x5a38
    std::uint16_t m_val = *(std::uint16_t*)m_arr;

    std::cout << std::hex << m_val << std::endl;

    return 0;
}

Upvotes: 0

Views: 99

Answers (2)

Barry
Barry

Reputation: 302663

Little endian means that the least significant byte goes first: enter image description here

So translate that logic to your array, { 0x5a, 0x38 }. On a little endian system, the 0x5a is least significant and 0x38 is most significant... hence you get 0x385a.

Upvotes: 1

zneak
zneak

Reputation: 138031

Byte ordering is the order in which bytes are laid out when referenced as their native type. Regardless of whether your machine is big or little endian, a sequence of bytes is always in its natural order.

The situation you describe (where the first byte is 0x38) is what you would observe if you created a uint16_t and got a uint8_t pointer to it. Instead, you have a uint8_t array and you get a uint16_t pointer to it.

Upvotes: 1

Related Questions