Search code examples
c++stlmemcpy

why std::copy in reverse order


I want to copy a sequence of bytes into integer values, presumably they will whim with the port's UPD

#include <iostream>
#include <cstring>

int main()
{
    uint8_t arr[8];
    uint32_t arrNew[2];

    arr[0] = 0x11;
    arr[1] = 0x22;
    arr[2] = 0x33;
    arr[3] = 0x44;
    arr[4] = 0x55;
    arr[5] = 0x66;
    arr[6] = 0x77;
    arr[7] = 0x88;

    memcpy(arrNew, arr, 8);

    std::cout << std::hex << arrNew[0] << "\n"; //out: 0x44332211
    std::cout << std::hex << arrNew[1] << "\n"; //out: 0x88776655

    return 0;
}

It should be: arrNew[0] = 0x11223344 arrNew[1] = 0x55667788.


Solution

  • This is a very fragile thing to do. As mentioned in one of the comments, it depends on the endianess. The number 0x01020304 can be stored:

    x01 x02 x03 x04

    But on others, it's the other way around. This is big-endian versus little-endian. A google for little endian vs. big endian will result in some great pages to read, so I'm not going to write it all here.

    On the hardware you're using, the endianess is opposite of what you expect.

    Basically, you can't assume. There are methods for dealing with network byte order. There's more information in this question: How do you write (portably) reverse network byte order?