Check Endianness with JavaScript

A very long time ago I wrote about endianness in computer systems. Determining the endianness of a system might be trivial with other languages but how you do same with JavaScript?

The challenge used to be with the absence of language primitives for direct binary manipulation in JavaScript. But guess what? TypedArrays and ArrayBuffers provide a neat way out.

If you want to do object manipulation at the binary level in JS (e.g. cryptography, image editing, audio etc), go explore ArrayBuffers, TypedArrays and DataViews.

How does it work?

This trick stores an unsigned array containing a single 32-bit value (there is no need for more values in the array).

Two key concepts:

1. Arrays store data in contiguous memory segments. So the 32 bit value representing the first element will be stored in the first 4 bytes.
2. The Uint32Array will store its elements in the native byte order of the computer system (e.g. either little or big endian)

Using these two constraints, it becomes possible to conclusively identify the endianness of the underlying computer system by mapping the entire 32-bit array to an 8-bit array and then reading the very first value!

Assuming we have 0x9876 as the four bytes in the value 0x9876 with 9 being the most significant byte and 6 being the least significant byte, then

Thus once we store any arbitrary value in a 32-bit store, all we have to do is read the first 8 bits to determine the underlying platform’s byte order.

Show me the code!

```let endianNess = () => {
let uInt32 = new Uint32Array([0x11223344]);
let uInt8 = new Uint8Array(uInt32.buffer);

if(uInt8[0] === 0x44) {
return 'Little Endian';
} else if (uInt8[0] === 0x11) {
return 'Big Endian';
} else {
return 'Maybe mixed-endian?';
}
};

endianNess();
```

What’s your computer endianness?

Test your understanding…

Is it possible to check with an Uint32Array containing more than one element? How would you do that?

Processing…
Awesome!

3 thoughts on “Check Endianness with JavaScript”

1. Anonymous says:

Hi, great article! I have followed your idea to build another solution to find the endianness of the platform. The prerequisite is: knowing a multi-bytes character and its UTF-8 bytes. For example, the character ɑ and its UTF-8 bytes are: C9 91. Thus we can do something like this with the switched bytes:

`new TextDecoder().decode(new Uint16Array([0x91c9])) === “ɑ” ? “Little endian” : “Big endian”`

It works because TextDecoder.decode() decodes only based on the pure bits in an ArrayBuffer and ignoring everything else. On the order hand, Uint16Array respects the endianness to create the underlying ArrayBuffer. So combine both facts, only little end can correctly decode the character.

Liked by 1 person

1. Anonymous says:

Glad to share. :) I also subscribed the blog. Thank you for those great articles!

Liked by 1 person

This site uses Akismet to reduce spam. Learn how your comment data is processed.