Not Available
Not Available

Reputation: 3355

Function that copies into byte vector reverses values

Hey, I've written a function to copy any variable type into a byte vector, however whenever I insert something it gets inserted in reverse.

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 whenever I add for example a uint16_t with the value 0x2f1f it gets inserted as 1f 2f instead of the expected 2f 1f.

What am I doing wrong here ?

Regards, Xeross

Upvotes: 2

Views: 389

Answers (3)

Didier Trosset
Didier Trosset

Reputation: 37447

You're not doing anything wrong. You are working on a little endian machine (e.g. Pentium). On these, the lower significant byte of a multiple bytes value is stored at the smallest address. Hence the result.

Upvotes: 4

James McNellis
James McNellis

Reputation: 355079

If you are on a little-endian machine (e.g., an x86), the bytes will appear reversed (i.e., the lower order bytes will appear before the higher order bytes).

If you really want to reverse the order of the bytes, you can use std::reverse.

Upvotes: 8

Related Questions