|
15.1.3 C EndiannessWhen a number longer than a single byte is stored in memory, it must be stored in some particular format. Modern systems do this by storing the number byte by byte such that the bytes can simply be concatenated into the final number. However, the order of storage varies: some systems store the least significant byte at the lowest address in memory, while some store the most significant byte there. These are referred to as little-endian and big-endian systems, respectively.(32) This difference means that portable code may not make any assumptions about the order of storage of a number. For example, code like this will act differently on different systems:
Although that was a contrived example, real problems arise when writing numeric data in a file or across a network connection. If the file or network connection may be read on a different type of system, numeric data must be written in a format which can be unambiguously recovered. It is not portable to simply do something like
i are the same on both
systems.
Instead, do something like this:
Another approach to handling endianness is to use the
These functions come in two sizes:
Although these functions are used in a lot of existing code, they can be
difficult to use in highly portable code, because they require knowing
the exact size of your data types. If you know that the type
int is not exactly 4 bytes long, this example will
not work correctly on all systems.
|