A function that copies into a byte vector changes values

Hey, I wrote a function to copy any type of variable to a byte vector, however whenever I insert something, it is inserted in reverse order.

Here's the code.

template <class Type>
void Packet::copyToByte(Type input, vector<uint8_t>&output)
{
    copy((uint8_t*) &input, ((uint8_t*) &input) + sizeof(Type), back_inserter(output));
}

      

Now when I add, for example, uint16_t with the value 0x2f1f, it is inserted as 1f 2f instead of the expected 2f 1f.

What am I doing wrong here?

Regards, Xeross

+2


a source to share


3 answers


If you are on little-endian (like x86) the bytes will appear backward (i.e. lower order bytes will appear before higher order bytes).



If you really want to change the byte order, you can use std::reverse

.

+8


a source


You are not doing anything wrong. You are running a small endpoint machine (eg Pentium). In this case, the least significant byte of a multi-byte value is stored at the lowest address. Hence the result.



+4


a source


0


a source







All Articles