Sub topic 8
Byte Order: Little-Endian and Big-Endian
This chapter assumes you know how to create typed arrays over an existing ArrayBuffer, and how several views can share one buffer. You should also be comfortable reading hexadecimal values such as 0x1234. Here you will learn why a multi-byte number can be stored in memory in two different ways, which way typed arrays use, and how to spot and fix byte-order bugs. The next chapter introduces DataView, the standard tool for controlling byte order directly.
The problem: one number, several bytes
A Uint8Array element is one byte, so there is only one way to store it. A Uint32Array element is four bytes. The value 0x01020304 breaks into the bytes 0x01, 0x02, 0x03, and 0x04. Memory addresses run from low to high, so the machine has to decide which byte goes at the lowest address.
- Big-endian stores the most significant byte first.
0x01020304becomes01 02 03 04, which reads the same way you write the number. - Little-endian stores the least significant byte first.
0x01020304becomes04 03 02 01.
The term endianness (or byte order) refers to this choice. Endianness only changes the order of whole bytes. The bits inside each byte stay in the same order.
Typed arrays use the platform's byte order
Multi-byte typed arrays (Uint16Array, Int32Array, Float64Array, and so on) read and write in the platform byte order, meaning the native order of the CPU running your code. The specification does not fix this order. In practice, almost every machine that runs JavaScript today is little-endian, including x86-64 and ARM as phones and Apple Silicon use it.
You can see the platform order by writing through a wide view and reading through a byte view:
const buf = new ArrayBuffer(4);
new Uint32Array(buf)[0] = 0x01020304;
const bytes = new Uint8Array(buf);
console.log(Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(' '));
// "04 03 02 01" on little-endian platformsFloating-point values follow the same rule. The 32-bit float 1.0 has the bit pattern 0x3F800000:
const f = new Float32Array([1.0]);
console.log(new Uint8Array(f.buffer)); // Uint8Array [0, 0, 128, 63] on little-endian128 is 0x80 and 63 is 0x3F, so the bytes appear lowest first.
Detecting the platform order
Code that has to be portable can check the order once at startup:
const isLittleEndian = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
console.log(isLittleEndian); // true on almost all current hardwareIf the lowest-address byte holds the 1, the least significant byte came first.
Where byte order is fixed by a format
File formats and protocols define their own byte order and ignore the platform's. The parser has to follow the format.
| Format or system | Byte order |
|---|---|
| TCP/IP headers ("network byte order") | Big-endian |
| PNG chunk lengths and fields | Big-endian |
| JPEG markers and segment lengths | Big-endian |
| WAV and BMP headers | Little-endian |
| ZIP headers | Little-endian |
| TIFF | Either; the file starts with `II` (little) or `MM` (big) |
| WebAssembly linear memory | Little-endian |
| x86-64 and typical ARM CPUs | Little-endian |
Some formats match your platform and some do not. TIFF shows that a format can even carry its byte order as data, which means the parser has to read a marker before it can read anything else.
The classic bug
Suppose a server sends a 16-bit big-endian length field with the value 0x1234 (4660). The bytes arrive as 12 34. Reading them through a Uint16Array gives the wrong number:
const received = new Uint8Array([0x12, 0x34]); // big-endian 0x1234 from the wire
const wrong = new Uint16Array(received.buffer)[0];
console.log(wrong.toString(16), wrong); // "3412" 13330 on little-endian
const right = (received[0] << 8) | received[1];
console.log(right.toString(16), right); // "1234" 4660Nothing throws an error. The value is simply wrong, often by a large amount. If a parsed length or count looks huge or unrelated to the data, suspect byte order first.
The second calculation is correct on every platform. It reads single bytes, and single bytes have no byte order, then combines them with shifts in the order the format requires.
Assembling values by hand
Shift-and-combine code works for any size up to 32 bits. Watch for one detail: JavaScript's bitwise operators produce signed 32-bit results. Shifting a byte of 0x80 or more left by 24 sets the sign bit, so you need >>> 0 to get an unsigned result.
function readUint32BE(bytes, i) {
return ((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]) >>> 0;
}
function readUint32LE(bytes, i) {
return ((bytes[i + 3] << 24) | (bytes[i + 2] << 16) | (bytes[i + 1] << 8) | bytes[i]) >>> 0;
}
const data = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
console.log(readUint32BE(data, 0).toString(16)); // "deadbeef"
console.log(readUint32LE(data, 0).toString(16)); // "efbeadde"If you leave out >>> 0, readUint32BE returns -559038737 for these bytes. Hand-written readers also work at any offset, unlike typed array views, which need an aligned byteOffset. You cannot assemble floats this way, though, because shifts work on integers only.
Swapping byte order
Sometimes you have a value or an array in one order and need the other.
Swapping a single 32-bit value
function swap32(x) {
return (
((x & 0xff) << 24) |
((x & 0xff00) << 8) |
((x >>> 8) & 0xff00) |
(x >>> 24)
) >>> 0;
}
console.log(swap32(0x01020304).toString(16)); // "4030201"The output has no leading zero because toString(16) drops it. The value is 0x04030201.
Swapping every element of a typed array in place
This works for any element type, floats included, because it reverses raw bytes and never interprets them as numbers:
function swapBytesInPlace(typed) {
const size = typed.BYTES_PER_ELEMENT;
const bytes = new Uint8Array(typed.buffer, typed.byteOffset, typed.byteLength);
for (let i = 0; i < bytes.length; i += size) {
bytes.subarray(i, i + size).reverse();
}
}
// 16-bit big-endian samples received from the network
const raw = new Uint8Array([0x00, 0x01, 0x01, 0x00, 0xff, 0xfe]);
const samples = new Uint16Array(raw.buffer);
const isLittleEndian = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
if (isLittleEndian) swapBytesInPlace(samples);
console.log(Array.from(samples)); // [1, 256, 65534]subarray shares memory, so reverse() changes the underlying buffer directly. The swap is only needed when the platform order differs from the data's order, which is why the code checks isLittleEndian first.
Edge cases and gotchas
- Bytes are unaffected.
Uint8Array,Int8Array, andUint8ClampedArraynever have byte-order issues. UTF-8 text is a byte sequence, so it has no byte order either. UTF-16 text does, which is why it sometimes starts with a byte order mark. - Your tests can hide the bug. If you write test data with a
Uint32Arrayand read it back with aUint32Array, the test passes even when the code would misread a real big-endian file. Build test inputs from explicit byte lists taken from the format specification. - Saving typed arrays to disk ties the file to the platform. Writing
new Float32Array(...).bufferstraight to a file stores the bytes in platform order. Document the order, or write the file with explicit-order code. - Sign extension when combining bytes. Reading a signed big-endian 16-bit value by hand needs an extra step:
((b0 << 8) | b1) << 16 >> 16sign-extends the result. - BigInt arrays follow platform order too.
BigInt64ArrayandBigUint64Arraystore eight bytes per element in native order.
Exercises
Exercise
On a little-endian machine, you run const u = new Uint16Array(new Uint8Array([0xab, 0xcd]).buffer); console.log(u[0].toString(16));. What is printed, and what would a big-endian machine print?
Show answer
Little-endian prints "cdab", because the byte at offset 0 (0xab) is the least significant. A big-endian machine prints "abcd".
Exercise
A ZIP header stores a 32-bit little-endian field at byte offset 14 of a Uint8Array named bytes. Why is new Uint32Array(bytes.buffer, 14, 1)[0] a poor way to read it, and what should you use instead with the tools from this chapter?
Show answer
Offset 14 is not a multiple of 4, so the constructor throws a RangeError. Even at an aligned offset, the result would only be correct on little-endian platforms. Use readUint32LE(bytes, 14), which combines the individual bytes with shifts and >>> 0. This works at any offset and on any platform. A DataView with littleEndian set to true, covered next, also works.
Exercise
Write a function readInt16BE(bytes, i) that returns a signed 16-bit big-endian value. Check it with the bytes [0xff, 0xfe].
Show answer
function readInt16BE(bytes, i) { return (((bytes[i] << 8) | bytes[i + 1]) << 16) >> 16; }. For [0xff, 0xfe] the combined value is 0xfffe (65534). Shifting left by 16 and then arithmetic-shifting right by 16 sign-extends it to -2.