I have a struct, which is composed of multiple 32 bits elements. I applied a #pragma pack (4), the following struct is therefore linear and aligned.
struct
{
int a; // 4 bytes
int b; // 4 bytes
int c; // 4 bytes
} mystruct; // total 16 bytes
How can I swap each of these elements (little -> big endian) ?
The method is void swap(void* a, int b);, with a pointer to the structure, and b integer giving the size of the structure.
For example :
void swap(void* a, int b)
{
//FIXME !
for (int i = 0; i < b; i+= 32)
{
a = (a & 0x0000FFFF) << 16 | (a & 0xFFFF0000) >> 16;
a = (a & 0x00FF00FF) << 8 | (a & 0xFF00FF00) >> 8;
a += 32;
}
}
You can swap two bytes without using a temporary:
Now let’s apply it to numbers of variable length
For your struct you can:
Of course, as an alternative to endianSwap using byteswap, we could just use std::reverse.