Skip to content

Instantly share code, notes, and snippets.

@jonathanlurie
Forked from TooTallNate/endianness.js
Last active July 12, 2017 00:38
Show Gist options
  • Save jonathanlurie/0893a08ebcf33594c70306c8931c9e20 to your computer and use it in GitHub Desktop.
Save jonathanlurie/0893a08ebcf33594c70306c8931c9e20 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"
// A shorter version
var a = new Uint32Array([0x12345678]);
var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
var BigEndian = (b[0] == 0x12);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment