2 ms·
For a long time, I struggled with endianness, because I thought that bitshifting and masking would be different on BE vs. LE: // wrong uint32_t num = .
by captainmuon 6y ago
For a long time, I struggled with endianness, because I thought that bitshifting and masking would be different on BE vs. LE:
// wrong
uint32_t num = ...;
// num is set to 0x10203040
num >> 24 == 0x10; // On little endian
num >> 24 == 0x10; // On big endian
Of course that is wrong, and the second one is always the case. In a way, you could say C/C++ is big endian - the higher valued byte is first (left in English reading order). In fact, if you avoid reinterpreting via casting / punning / memcpy, you don't have to think about it at all [1].
One thing I have to do frustratingly often is to implement a bunch of functions like "read_uint32_le", it is a pity that there is no comprehensive standard.
([1] On the other hand, I miss the good old days where you could treat C like "high level assembler", a pointer was just a number that indexed memory, and you could reinterpret bytes with impunity - sometimes had to to get decent performance!)