Microprocessor architectures commonly use two different byte-ordering methods (little-endian and big-endian) to store the individual bytes of multibyte data formats in memory. This difference becomes critically important if you try to read data from files that were created on a computer that uses a different byte ordering than yours. You also need to consider byte ordering when you send and receive data through a network connection and handle networking data. The difference in byte ordering can produce incorrect results if you do not account for this difference. For example, the order of bytes in memory of a scalar type is architecture-dependent, as shown in Listing 2-1.
Listing 2-1 Code that illustrates byte-ordering differences
unsigned char charVal; |
unsigned long value = 0x12345678; |
unsigned long *ptr = &value; |
charVal = *(unsigned char*)ptr; |
On a processor that uses little-endian addressing the variable charVal takes on the value 0x78. On a processor that uses big-endian addressing the variable charVal takes on the value 0x12. To make this code architecture-independent, change the last line in Listing 2-1 to the following:
charVal = (unsigned char)*ptr;
For a detailed discussion of byte ordering and strategies that you can use to account for byte-ordering differences, see “Swapping Bytes.”
Last updated: 2007-02-26