Is reading one byte at a time endianness agnostic regardless of value size?
If I read/write one byte at a time to/from a stream and shift each byte like the below examples, will the results be consistent regardless of machine endianness?
Yes. Your s_write_uint32()
function stores the bytes of the input value in order from least significant to most significant, regardless of their order in the native representation of that value. Your s_read_uint32()
correctly reverses this process, regardless of the underlying representation of uint32_t
. These work because
- the behavior of the shift operators (
<<
,>>
) is defined in terms of the value of the left operand, not its representation - the
& 0xff
masks off all bits of the left operand but those of its least-significant byte, regardless of the value's representation (because0xff
has a matching representation), and - the
|=
operations just put the bytes into the result; the positions are selected, appropriately, by the preceding left shift. This might be more clear if+=
were used instead, but the result would be no different.
Note, however, that to some extent, you are reinventing the wheel. POSIX defines a function pair htonl()
and nothl()
-- supported also on many non-POSIX systems -- for dealing with byte-order issues in four-byte numbers. The idea is that when sending, everyone uses htonl()
to convert from host byte order (whatever that is) to network byte order (big endian) and sends the resulting four-byte buffer. On receipt, everyone accepts four bytes into one number, then uses ntohl()
to convert from network to host byte order.