liveBook · Manning

Endianness

As explained in Modern C, Third Edition

Endianness is the ordering convention used to encode the bytes of multi-byte values in a representation.

Endianness is the ordering convention used to encode the bytes of a multi-byte value in memory or another representation. For an unsigned value such as 0xAABBCCDD, the bytes may appear from low-order to high-order, or in the reverse order. The C standard does not normalize this ordering; the observed arrangement is implementation-defined. section 12.2

Inspecting an integer's bytes

A union can overlay an unsigned value with an array of unsigned char, allowing its object representation to be inspected. With twofold.val set to 0xAABBCCDD, one observed machine prints byte[0] as 0xDD, followed by 0xCC, 0xBB, and 0xAA. This arrangement places the low-order representation digits before the high-order digits. section 12.2

typedef union unsignedInspect unsignedInspect;
union unsignedInspect {
  unsigned val;
  unsigned char bytes[sizeof(unsigned)];
};
unsignedInspect twofold = { .val = 0xAABBCCDD, };

Use the union definition to inspect an unsigned value through its individual unsigned-char bytes. section 12.2

Endianness matters when representations cross program or platform boundaries:

  • Treat raw binary files as portable only between executions and platforms using the same representation, including the same endianness. section 14.6
  • Open streams in binary mode when using fread or fwrite; otherwise, platform-specific transformations can undermine reliable transport of representations. section 14.6
  • Do not assume that different platforms, operating systems, or program executions encode objects with the same byte ordering. section 14.6

How Modern C, Third Edition covers it

How deep it goes
Demonstrates byte inspection with a union and output, then stops short of standardizing the observed ordering.
Examples
Uses a 0xAABBCCDD unsigned value, a byte-inspecting union, and fread/fwrite binary-stream guidance.
What it assumes
Assumes familiarity with C unions, arrays, unsigned values, and object representations while defining ordering through a concrete example.
What you can do after
Diagnose byte ordering by overlaying an unsigned value with an unsigned-char array and interpret binary portability limits.
How it connects
Connects unions, object representation, unsigned char, binary streams, and binary mode.

Also explained in

Compare how 3 books explain endianness →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.