November 23, 2013

Endianness in Javascript

I just needed to determine endianness from Javascript; this is needed because ArrayBuffer and associated classes operate directly upon memory buffers, which is great when you want to slurp in some binary data without the overhead of JSON-conversion, but does imply an endianness dependency.

I probably could have just ignored the question (at the expense of all my Alpha-powered users), but I'm OCD enough to write the check.

function littleEndian() {
  var buf = new ArrayBuffer(4);
  var bytes = new Uint8Array(buf);
  var words = new Uint32Array(buf);
  bytes[0] = 1;
  return words[0] == 1; // little-endian
}

But I can't test it.

2 comments:

Unknown said...

returns true on my MacBook Air on Mavericks if you care.

Unknown said...

Glad to hear it, that's basically the same system I developed it on. After some research, the only known ways to test it big-endian is an independent Firefox 4 port to PPC Mac or possibly bringing up a big-endian Linux/*BSD on an emulator. Either of which is more work than I care to do.