← Runtimes
Runtimes

Endianness and byte order

How a multi-byte number sits in memory, and how a format says to write it.

Separate a number’s value from the byte order used to store or transmit it.

Outcome

Predict how a multi-byte number is stored on a little-endian machine, read and write numbers in a format’s stated byte order, and decode messages whose parts use different orders.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Big-endian
Storing or sending the most significant byte first.
Little-endian
Storing or sending the least significant byte first.
Native byte order
The native scalar/element byte order of the execution profile. The JavaScript probe exposes its runtime’s typed-array element order.
Network byte order
Big-endian, the conventional order for internet protocol headers.
DataView
A JavaScript view of buffer bytes. Multi-byte integer operations default to big-endian and accept an explicit littleEndian flag; one-byte operations do not need it.

What byte order describes

Endianness describes the order of bytes within a multi-byte value. Big-endian places the most significant byte first; little-endian places the least significant byte first. “First” means the lowest address in a memory inspection or the earliest byte in a serialized field. The value itself has no byte order until a representation is chosen.

Native order describes one execution profile. A file or message format declares its own order, together with field widths and signedness. Reading intact bytes with the wrong rule can change their interpreted value, so identify the field’s schema before decoding it.

01In memory

How does the machine store a 32-bit number?

The chilled-load alarm is based on 58.88 °C, while the probe value is 0.23 °C. The tracker report’s temperature bytes reached the gateway intact as 00 17. Use a distinctive four-byte vehicle id to separate native memory order from the report’s encoding, then follow the relayed probe readings through conversion.

Reduce the failing report to a known pattern with four distinct bytes. In these eight-bit-octet profiles, a 32-bit field occupies four bytes. Big-endian puts the most significant byte first; little-endian puts the least significant byte first. The recorded profiles are little-endian. ARM supports configurable data order, so inspect the actual profile rather than inferring it from ARM64 alone.

The diagnostic vehicle id is 0x0A0B0C0D. Each source reports its native/runtime element bytes in address order. This establishes a byte-order observation, not a memory-layout claim about all values in the language.

A Uint8Array over the Uint32Array’s buffer exposes the runtime’s native element order, little-endian in this Node profile. ECMAScript’s agent chooses that order; the language does not fix all typed arrays to little-endian.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Stores vehicle id 0x0A0B0C0D in a 32-bit typed array and looks at the bytes.

const vehicleIds = new Uint32Array([0x0a0b0c0d]);
const inMemory = new Uint8Array(vehicleIds.buffer);

const hex = (bytes: Uint8Array) =>
  Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(" ");

console.log(`typed array bytes: ${hex(inMemory)}`);
For the recorded little-endian profile, which byte sequence do the inspection programs report for 0x0A0B0C0D?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict && node main.ts

The quoted outputs are historical observations from the recorded little-endian ARM64 profiles, not new runs in this revision. These examples use eight-bit octets and exact-width integer fields of 16 and 32 bits. Native inspection can differ on another configured target; explicit format encoders follow their stated byte order.

02In a format

How do you write a number for a file or the network?

The memory dump explains the gateway’s mistaken assumption, but the sender’s schema decides what the received bytes mean. Big-endian is the conventional network order used by many Internet headers; application formats can choose otherwise. The authored tracker report here specifies big-endian fields. Encode their values in that order so the report does not depend on the sender’s native representation.

DataView reads and writes numbers at byte offsets; each method takes an optional littleEndian flag.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Writes vehicle id 0x0A0B0C0D for a network report with DataView.

const vehicleId = 0x0a0b0c0d;
const view = new DataView(new ArrayBuffer(4));
view.setUint32(0, vehicleId);

const hex = (bytes: Uint8Array) =>
  Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(" ");

console.log(`DataView default: ${hex(new Uint8Array(view.buffer))}`);
view.setUint32(0, vehicleId, true);

console.log(`littleEndian = true: ${hex(new Uint8Array(view.buffer))}`);
What does the first line, written with DataView’s default, print?

03Mixed messages

What happens when the orders disagree?

Correcting the fixed tracker report does not settle the relay path. The tracker’s authored envelope has a big-endian vehicle id and a one-byte count, followed by that many two-byte probe values. The chosen Bluetooth Temperature characteristic (0x2A6E) uses a signed 16-bit value with 0.01 °C resolution and little-endian fields. Relaying those bytes unchanged puts both orders into this envelope. Preserve the record sequence while decoding each value and re-encoding the outgoing body.

The same two bytes, 01 2c, read two ways
Read asHigh byteValue
Big-endian010x012c
Little-endian2c?
A tracker sends sequence number 300 big-endian, as the bytes 01 2c. A gateway reads those two bytes as little-endian. What number does it get?

04Practice

Finish the fleet telemetry gateway

The gateway exercise isolates three codec operations: read a two-byte sequence field; decode an eight-byte tracker report containing id, signed temperature and flags; then construct a counted probe-body translation. It reads complete well-formed hex frames from stdin, without network or Bluetooth I/O. The Medium starter’s native-order fault is exposed on the recorded little-endian profile. Correct explicit-order solutions do not depend on that fault remaining visible on every host.

The fleet telemetry gateway

Read a tracker’s sequence number, decode a tracker report, then translate a probe packet with a mixed byte order.

  1. easy · R-ENDIAN-V4-1 Read a 16-bit field
  2. medium · R-ENDIAN-V4-2 Decode a packet
  3. hard · R-ENDIAN-V4-3 Translate a mixed packet
In the frontend Display a decoded temperature Optional

The UI receives a signed raw integer after byte decoding. Temperature characteristic 0x2A6E uses hundredths of a degree Celsius and reserves -32768 for value not known. This display step cannot detect a decoder that turned 23 into 5888: both are representable values. Check the codec before trusting the alarm.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function formatCelsius(raw: number): string {
  if (raw === -32768) return "Unknown";
  if (!Number.isInteger(raw) || raw < -27315 || raw > 32767) return "Invalid value";

  return (raw / 100).toFixed(2) + " °C";
}

export default function Temperature({ rawHundredths }: { rawHundredths: number }) {
  return <output>{formatCelsius(rawHundredths)}</output>;
}

The prop is already decoded. The component preserves the unknown sentinel as a label rather than presenting it as a physical measurement.

Sources: Bluetooth SIG: Temperature range, resolution and unknown value.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.