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

Endianness 0x9876 representation
Little 0x6789
Big 0x9876

 

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?

Leave a Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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