Endian Byte Order

In computing, endianness is the byte ordering used to store binary data in memory. When specifically talking about bytes, endianness is also referred to simply as byte order.

Computers store multi-byte data in different formats. They could either be stored starting with the least significant byte to the most significant byte or vice versa.

To further illustrate, let’s go through a few examples that refer to a 32-bit value, 0x12345678, stored in memory.

Big-Endian

In big-endian architectures, the MSB (most significant byte) value, which is 0x12 in our example, is stored at the memory location with the lowest address, the next byte value in significance, 0x34, is stored at the following memory location and so on. This is akin to Left-to-Right reading order in hexadecimal.

increasing addresses
0x12 0x34 0x56 0x78
Little-Endian

In little-endian architectures, the LSB (least significant byte) value, 0×78, is at the lowest address. The other bytes follow in increasing order of significance.

increasing addresses
0x78 0x56 0x34 0x12
Middle-Endian

There are some architectures that may have a more complicated ordering. The 32-bit data is broken into two 16-bit data, and each half is stored in little-endian format. This ordering is also known as PDP-endianness. This endian format is not very popular.

increasing addresses
0x34 0x12 0x78 0x56
Network Order

As every computer architecture is different, there needs to be a common endian format when exchanging data between computers over a network. The standard network order is big-endian and is usually called network order.

Writing Portable Code

Portable network programs written in the C language for the UNIX platform usually use the following functions to convert data between the host and network byte order. The functions will reorder the bytes depending on the byte order of the native architecture.

uint32_t htonl(uint32_t hostlong);   /* host to network long   */
uint16_t htons(uint16_t hostshort);  /* host to network short  */
uint32_t ntohl(uint32_t netlong);    /* network to host long   */
uint16_t ntohs(uint16_t netshort);   /* network to host short  */

The above functions are also available in Microsoft Windows as part of the Windows Socket API.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react, vuejs); plays_on(xbox, ps4); linux_desktop_user(true); }