UNIX to Linux Porting: A Comprehensive Reference

F.4. Byte Ordering

The term byte ordering refers to the order in which the bytes of a word are stored in memory. You can store 32-bit binary values, such as 4A3B2C1D, in several ways, including the following:

  • A big-endian scheme stores the most significant byte (MSB) first, yielding

    0x4A 0x3B 0x2C 0x1D

  • A little-endian scheme stores the least significant byte (LSB) first, yielding

    0x1D 0x2C 0x3B 0x4A

The IBM zSeries is big-endian system. When porting source code that was originally developed for a machine that is little-endian, you might occasionally stumble over subtle problems. The Endianess Checking Tool, provided as part of IBM's Migration Kit for Solaris OS to Linux,[17] can help you locate parts of your code that depend on endianness.

[17] http://www-1.ibm.com/partnerworld/pwhome.nsf/weblook/pat_linux_migrate_solaris.html

If you need to support multiple platforms with different endianness, you can include the Linux kernel header file asm/byteorder.h, which defines one of the two symbols __BIG_ENDIAN and __LITTLE_ENDIAN, respectively, depending on the machine's endianness. The header files found in /usr/src/linux/include/linux/byteorder/ provide macros for converting between big- and little-endian representations. If the order is the same, they do nothing. Otherwise, the macros return the converted value.

A set of similar functions handle byte-order issues related to data transferred via the network. These functions, declared in /usr/include/netinet/in.h, convert values between the network and host byte order. Note that networks often use big-endian byte order, so an application running on zSeries does not need a conversion here. It is, however, good programming practice to insert appropriate conversion routines.

Категории