Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created February 10, 2013 20:32
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save TooTallNate/4750953 to your computer and use it in GitHub Desktop.
Save TooTallNate/4750953 to your computer and use it in GitHub Desktop.
Get host machine endianness using JavaScript Typed Arrays (polyfill for `os.endianness()` in node.js)
function endianness () {
var b = new ArrayBuffer(4);
var a = new Uint32Array(b);
var c = new Uint8Array(b);
a[0] = 0xdeadbeef;
if (c[0] == 0xef) return 'LE';
if (c[0] == 0xde) return 'BE';
throw new Error('unknown endianness');
}
endianness();
// "LE"
@symil
Copy link

symil commented Nov 8, 2017

One line version:

var isBigEndian = new Uint8Array(new Uint32Array([0x12345678]).buffer)[0] === 0x12;
var isLittleEndian = new Uint8Array(new Uint32Array([0x12345678]).buffer)[0] === 0x78;

@michau-krakow
Copy link

Be careful with this one-line code - you can't blindly trust TypedArray.buffer property: see notes on https://nodejs.org/api/buffer.html#buffer_buf_buffer and https://nodejs.org/api/buffer.html#buffer_buf_byteoffset

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment