Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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"
@gamealchemist

This comment has been minimized.

Copy link

commented Oct 5, 2013

Thx, mate.

@jn0

This comment has been minimized.

Copy link

commented Feb 14, 2017

👍 Ended up with a bit shorter code :)

        var a = new Uint32Array([0x12345678]);
        var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
        var BigEndian = (b[0] == 0x12);
@ghost

This comment has been minimized.

Copy link

commented Feb 21, 2017

@jn0 Yea, looks gad

@Anovs

This comment has been minimized.

Copy link

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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.