Endianness from what I understand, is when the bytes that compose a multibyte word differ in their order, at least in the most typical case. So that an 16-bit integer may be stored as either 0xHHLL or 0xLLHH.
Assuming I don’t have that wrong, what I would like to know is when does Endianness become a major factor when sending information between two computers where the Endian may or may not be different.
-
If I transmit a short integer of 1, in the form of a char array and with no correction, is it received and interpretted as 256?
-
If I decompose and recompose the short integer using the following code, will endianness no longer be a factor?
// Sender: for(n=0, n < sizeof(uint16)*8; ++n) { stl_bitset[n] = (value >> n) & 1; }; // Receiver: for(n=0, n < sizeof(uint16)*8; ++n) { value |= uint16(stl_bitset[n] & 1) << n; }; -
Is there a standard way of compensating for endianness?
Very abstractly speaking, endianness is a property of the reinterpretation of a variable as a char-array.
Practically, this matters precisely when you
read()from andwrite()to an external byte stream (like a file or a socket). Or, speaking abstractly again, endianness matters when you serialize data (essentially because serialized data has no type system and just consists of dumb bytes); and endianness does not matter within your programming language, because the language only operates on values, not on representations. Going from one to the other is where you need to dig into the details.To wit – writing:
Here we could just have said,
reinterpret_cast<unsigned char *>(&n), and the result would have depended on the endianness of the system.And reading:
Again, here we could have said,
uint32_t n = *reinterpret_cast<uint32_t*>(buf), and the result would have depended on the machine endianness.As you can see, with integral types you never have to know the endianness of your own system, only of the data stream, if you use algebraic input and output operations. With other data types such as
double, the issue is more complicated.