# 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 === 0x44) {
return 'Little Endian';
} else if (uInt8 === 0x11) {
return 'Big Endian';
} else {
return 'Maybe mixed-endian?';
}
};

endianNess();
```