Byte Endianness in JavaScript

Byte Endianness in JavaScript

·

2 min read

Byte endianness is about how the computer interprets bytes.

Say we have 4 bytes 0xaa, 0xbb, 0xcc, 0xdd and we want to interpret these 4 bytes into a number, specifically a unsigned 32-bit interger. Basically, there are 2 ways computers interpret them: 0xaabbccdd or 0xddccbbaa. The first one is called big endianness, then the second one is called small endianness. You can see the difference more clearly in below.

0xaa, 0xbb, 0xcc, 0xdd

0xaabbccdd => big endianness
0xddccbbaa => small endianess

So we must know the byte endianness before we can read/write data properly.

In javascript, which endianness is used depends on the underlying CPU architecture.

So how can we know which one is used in runtime? We can check it like below.

const v = new Uint32Array(new Uint8Array([0xaa, 0xbb, 0xcc, 0xdd]).buffer)[0]

// is big endianness?
v === 0xaabbccdd
// false

// is small endianness?
v === 0xddccbbaa
// true

OK, now we know the endianness, then we can assemble data in the right byte order manually.

Or, we can use Data view api to assemble data, which we can pass endianness parameters and the api will do the hard working for us.

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

new Uint8Array(arrayBuffer)
// Uint8Array(4) [0, 0, 0, 0, buffer: ArrayBuffer(4), byteLength: 4, byteOffset: 0, length: 4, Symbol(Symbol.toStringTag): 'Uint8Array']

// write value in little endinness
view.setUint32(0, 0xaabbccdd, true)

new Uint8Array(arrayBuffer)
// Uint8Array(4) [221, 204, 187, 170, buffer: ArrayBuffer(4), byteLength: 4, byteOffset: 0, length: 4, Symbol(Symbol.toStringTag): 'Uint8Array']

// write value in big endinness
view.setUint32(0, 0xaabbccdd, false)

new Uint8Array(arrayBuffer)
// Uint8Array(4) [170, 187, 204, 221, buffer: ArrayBuffer(4), byteLength: 4, byteOffset: 0, length: 4, Symbol(Symbol.toStringTag): 'Uint8Array']

// read value in little endianness
view.getUint32(0, true)
// 3721182122

// read value in big endianness
view.getUint32(0, false)
// 2864434397