Byte order in typed arrays and DataView

suggest change

Endianness describes the order of bytes in a multibyte value. Little-endian systems store the least significant byte at the lowest address; big-endian systems store the most significant byte first.

Typed arrays use the platform's native byte order. The following check reveals that order by viewing the same buffer as a 16-bit value and as bytes:

function isLittleEndian() {
  const buffer = new ArrayBuffer(2);
  new Uint16Array(buffer)[0] = 0x00ff;
  return new Uint8Array(buffer)[0] === 0xff;
}

Do not depend on native byte order when reading or writing a file format or network protocol. DataView lets the program state the intended order explicitly; its multibyte methods default to big-endian when the optional littleEndian argument is omitted or false.

const buffer = new ArrayBuffer(4);
const view = new DataView(buffer);

view.setUint32(0, 0x11223344, false); // Big-endian
console.log([...new Uint8Array(buffer)]); // [17, 34, 51, 68]

view.setUint32(0, 0x11223344, true);  // Little-endian
console.log([...new Uint8Array(buffer)]); // [68, 51, 34, 17]

Ordinary bitwise operators work with numeric values, not byte sequences, so their results do not depend on the host's byte order. Endianness becomes observable only when the same ArrayBuffer bytes are interpreted through multibyte views.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents