Section 4.21

Endianness

Definition

Endianness, also called byte order, is the rule that fixes the order in which the bytes of a multi-byte number are stored in memory or sent over a link. Big-endian order puts the most significant byte, the one with the largest place value, first, at the lowest address; little-endian order puts the least significant byte first. The rule applies only when several bytes are read as one number, or one number is written as several bytes. Each processor, file format and protocol fixes its own byte order.

The idea

A sensor sends the 32-bit count 305,419,896 to a laptop over a link that carries one byte at a time. In hexadecimal notation (base 16, marked by the prefix 0x) the count is 0x12345678. Two hexadecimal digits make one byte, so the count is the four bytes 12, 34, 56 and 78, and 12 is the most significant. If the sensor sends 78 first and the laptop takes the first byte as the most significant, the laptop computes 0x78563412, which is 2,018,915,346. Every byte arrived intact; the two sides disagree only about which position carries which place value.

Dates show the same problem: 2026-11-18 and 18-11-2026 are the same three parts in two orders, and a reader must know the convention. Written decimal numbers put the most significant digit first, which is the big-endian convention. The comparison stops at the byte. A byte is the smallest unit that memory addresses and that a link hands to software, so its 8 bits travel together as one value from 0 to 255, and byte order never changes the bits inside a byte.

Neither order is better in every respect. Little-endian order keeps the lowest byte of a number at its first address whether the number is stored in 2, 4 or 8 bytes; big-endian order matches written numbers, so a printout of memory reads naturally. x86 processors and most Arm systems run little-endian. The headers of the core Internet protocols are big-endian, which is why big-endian order is also called network byte order; Bluetooth Low Energy §7.1, by contrast, sends its multi-byte fields little-endian. The names come from Jonathan Swift’s novel Gulliver’s Travels (1726), whose nations fight over which end of an egg to break. Danny Cohen applied them to computers in a 1980 note, “On Holy Wars and a Plea for Peace” [454].

How it works

Two byte orders meet whenever a number enters or leaves a program:

A program converts between the two exactly once, at that boundary. Turning numbers into external bytes is part of serialization §4.28; turning external bytes back into numbers is part of deserialization §4.29.

One portable method computes each external byte from the numeric value. To see how it works, use a four-byte field:

  1. Encode. To write an unsigned 32-bit value x as a big-endian field, take byte 0 as x >> 24, byte 1 as (x >> 16) & 0xFF, byte 2 as (x >> 8) & 0xFF and byte 3 as x & 0xFF. Here >> shifts a value right by the given number of bit positions, and & 0xFF keeps its lowest 8 bits. A little-endian field takes the same four bytes in the opposite order.

  2. Decode. To read a big-endian field from the bytes b[0] to b[3], compute

    ((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16)
    | ((uint32_t)b[2] << 8) | (uint32_t)b[3]

    where << shifts left and |, bitwise OR, joins the four parts, which do not overlap. A little-endian field gives b[3] the shift by 24 and b[0] none.

  3. Check. Before decoding, check that all four bytes are in the buffer; after decoding, check the value’s range before using it as a length, an offset or an index.

Shifts act on the value of x, not on the bytes that hold it, so this code gives the same external bytes on every host. Each byte is converted to uint32_t, an unsigned integer type of exactly 32 bits, before it is shifted. Otherwise C converts it to int first (integer promotion §4.18), and shifting a byte of 0x80 or more left by 24 positions into the sign bit of a 32-bit int is undefined behavior §4.12. If the uncast byte promotes to a 16-bit int, a shift by 24 exceeds the width of that operand. The cast shown above gives the shift a 32-bit operand on that host.

The POSIX (Portable Operating System Interface) functions htonl and ntohl, read as “host to network long” and back, convert 32-bit values between host order and network order; htons and ntohs do the same for 16-bit values. On a big-endian host they return their argument unchanged, and on a little-endian host they reverse its bytes. For a big-endian wire field, a sender can store the result of htonl(x) in a uint32_t and copy its four bytes into the message. A receiver can copy those bytes into a uint32_t and apply ntohl to recover the numeric value. Taking the bytes of the original host integer would give the wrong order on a little-endian host. For little-endian fields, the C libraries of Linux systems provide functions such as htole32 and le32toh.

Worked example

Decode the four received bytes 12 34 56 78 under each rule. Number them b0b_0 to b3b_3 in arrival order; in decimal they are b0=18b_0 = 18, b1=52b_1 = 52, b2=86b_2 = 86 and b3=120b_3 = 120. Each step of one position multiplies the place value by 256, because a byte has 256 possible values, so the place values are 2563=16,777,216256^3 = 16{,}777{,}216, 2562=65,536256^2 = 65{,}536, 256256 and 11. big-endian:18×16,777,216+52×65,536+86×256+120=301,989,888+3,407,872+22,016+120=305,419,896,little-endian:120×16,777,216+86×65,536+52×256+18=2,013,265,920+5,636,096+13,312+18=2,018,915,346.\begin{aligned} \text{big-endian:}\quad & 18 \times 16{,}777{,}216 + 52 \times 65{,}536 + 86 \times 256 + 120 \\ &= 301{,}989{,}888 + 3{,}407{,}872 + 22{,}016 + 120 = 305{,}419{,}896, \\ \text{little-endian:}\quad & 120 \times 16{,}777{,}216 + 86 \times 65{,}536 + 52 \times 256 + 18 \\ &= 2{,}013{,}265{,}920 + 5{,}636{,}096 + 13{,}312 + 18 = 2{,}018{,}915{,}346. \end{aligned} The first result is 0x12345678 and the second is 0x78563412.

A sensor sends the two bytes FF 80. Big-endian decoding gives the bit pattern 0xFF80. As an unsigned 16-bit quantity it is 255×256+128=65,408255\times256+128=65{,}408. As a signed 16-bit two’s-complement reading it is 65,408−65,536=−12865{,}408-65{,}536=-128, since its top bit is set. A little-endian reader assembles 0x80FF instead, which is 33,023 unsigned or −32,513-32{,}513 signed. Read the field specification for both decisions: which byte is most significant, and how to interpret the assembled bits.

The error does most harm in a length field. A message begins with a 2-byte length, sent as 00 10. A big-endian reader computes 0×256+16=160 \times 256 + 16 = 16 bytes; a little-endian reader computes 0+16×256=40960 + 16 \times 256 = 4096 bytes. If the receive buffer holds only this message, a parser that uses 4096 without comparing it with the number of bytes received performs an out-of-bounds read §4.5 of up to 4096−16=40804096 - 16 = 4080 bytes. The decoding itself stayed inside the buffer; the wrong place values caused the overrun.

Host order shows when memory is copied. On a little-endian host, uint32_t x = 0x12345678; at address 0x20000000 is stored as 78 at 0x20000000, then 56, 34 and 12 at the next three addresses. Sending x by copying its memory sends 78 56 34 12 there and 12 34 56 78 on a big-endian host. The shift encoder above sends 12 34 56 78 on both.

Stated precisely

Let nn be the number of bytes in a field, and let b0,b1,…,bn−1b_0, b_1, \dots, b_{n-1} be its bytes in order of increasing address or of transmission, each an integer from 0 to 255. The field’s value is Vbig=∑j=0n−1bj⋅256n−1−jorVlittle=∑j=0n−1bj⋅256j.V_{\text{big}} = \sum_{j=0}^{n-1} b_j \cdot 256^{\,n-1-j} \qquad\text{or}\qquad V_{\text{little}} = \sum_{j=0}^{n-1} b_j \cdot 256^{\,j}. Conversely, a value VV with 0≤V<256n0 \le V < 256^n is encoded little-endian as bj=⌊V/256j⌋mod256b_j = \lfloor V / 256^j \rfloor \bmod 256, where ⌊x⌋\lfloor x \rfloor is xx rounded down and amodma \bmod m is the remainder of aa divided by mm. The big-endian encoding is the same nn bytes in reverse order.

The contract between an encoder and a decoder is decode(encode(V))=V\mathrm{decode}(\mathrm{encode}(V)) = V for every VV from 0 to 256n−1256^n - 1, with both using the order that the format specifies. The formulas assume three things.

  1. 8-bit bytes. C allows bytes of more than 8 bits, and some digital signal processors use 16-bit bytes; for ww-bit bytes the base is 2w2^w instead of 256.

  2. An unsigned field. In a signed field stored in two’s complement form, the usual form of negative integers, a decoded V≥28n−1V \ge 2^{8n-1} means V−28nV - 2^{8n}. The 2-byte big-endian field FF FE decodes to 65,534, which is at least 215=32,7682^{15} = 32{,}768, so it means 65,534−65,536=−265{,}534 - 65{,}536 = -2.

  3. One order per field. Some old machines mixed orders: the PDP-11 minicomputer (Programmed Data Processor) stored the 32-bit value 0x0A0B0C0D as 0B 0A 0D 0C.

Limits and common mistakes

Byte order is not bit order. The byte 0x12, binary 00010010, keeps its 8 bits in both orders; reversing them would give 0x48, a different operation. The order in which a serial link sends the bits of each byte is a rule of the physical link, and the receiving hardware rebuilds each byte before software sees it.

A byte string has no byte order. Text, a cryptographic hash §5.1, a key or an encrypted message is defined byte by byte. Reversing it because the host is little-endian corrupts it.

Host order is not a file or wire format. Copying an integer variable or a C structure to a file or a link emits host byte order, and for a structure also the unused bytes that the compiler inserted between members (struct padding §4.27).

Convert exactly once. A second conversion undoes the first on a little-endian host and does nothing on a big-endian one, so the bug shows on one kind of machine only. Test against a fixed example from the format’s specification. A round trip through one’s own encoder and decoder passes even when both use the wrong order.

Do not cast the buffer. Converting the buffer’s address to a uint32_t pointer and reading through it converts no byte order, may break the alignment §4.22 that uint32_t requires, and may break C’s strict aliasing rule §4.23.

Correct decoding is not validation. Endianness says nothing about a field’s width, signedness, unit or permitted range.

Questions answered

Does a byte array §14.5 have endianness before it is interpreted as a number?

No. A byte array is a sequence of single bytes at numbered positions; that order is simply the order of the sequence, and a single byte has no byte order. Endianness, the rule that assigns place values to the bytes of a multi-byte number, appears only when code reads several bytes as one number or writes one number as several bytes. The bytes 12 34 56 78 (hexadecimal) mean 0x12345678, which is 305,419,896, under the big-endian rule (most significant byte first), and 0x78563412, which is 2,018,915,346, under the little-endian rule (least significant byte first). Until a rule is applied, they are just four bytes.

Endianness therefore belongs to the format that defines each field, not to the buffer that holds the bytes. One message can contain a big-endian field, a little-endian field and a text string that has no byte order at all. A byte string such as a cryptographic hash or a key is never reversed for byte order, whatever the host processor’s own order is.

Related entries: Alignment (§4.22), Strict aliasing and effective type (§4.23), Struct padding and packing (§4.27), Serialization (§4.28), struct module (§12.38), Deserialization (§4.29), Shift semantics (§4.20). Further reading: [78, 162, 454].