1

JavaScript Typed Arrays pose a danger when it comes to endianness.

Suppose that you have a function like this:

var encodeFloat32 = (function() {
  var arr  = new Float32Array( 1 );
  var char = new Uint8Array( arr.buffer );
  return function( number ) {
    arr[0] = number;
    return String.fromCharCode( char[0], char[1], char[2], char[3] );
  };
}());

This is a potentially dangerous function if you were to run it on a Big Endian system due to the order in which you submit the ArrayBuffers bytes to the "fromCharCode" method.

Therefore you would need to create some kind of endian safety in order to make your code platform-independent.

What is the best practice to create "endian safety" across an application written in JavaScript? Are there any workarounds?

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Willem
  • 1,094
  • 1
  • 12
  • 23

2 Answers2

1

According to this post endianess is safe in JavaScript

JavaScript Endian Encoding?

Look at the DataView object (still in draft) which sould be useful to your requirements since it provides a littleEndian boolean

Community
  • 1
  • 1
lostsource
  • 21,070
  • 8
  • 66
  • 88
  • 2
    I believe that article was posted before Typed Arrays arrived in JavaScript. It explains that bit shifting is endian safe but I don't think it applies to Typed Arrays. – Willem Nov 10 '12 at 20:27
  • DataView looks promising, but I am unsure as to how you would actually use it to implement the endian safety. – Willem Nov 10 '12 at 20:30
  • my assumption is that if you always read/write values via DataView you can sort of 'ignore' the endianess of the platform. (again this is an assumption I have nothing to proove it) This post might be helpful http://stackoverflow.com/a/7876265/149636 – lostsource Nov 10 '12 at 20:41
  • 1
    [`DataView` gives you a boolean `littleEndian` to set](http://www.khronos.org/registry/typedarray/specs/latest/#8). This is definitely the way to go, as it is designed to solve exactly this "problem". – Lightness Races in Orbit Nov 10 '12 at 20:48
  • @LightnessRacesinOrbit thanks for the link, I added it to the answer – lostsource Nov 10 '12 at 20:56
  • How would one use it to solve e.g. the function in the original post? Does anone have a good structure for implementing this across the whole application? – Willem Nov 10 '12 at 21:45
1

I use a function like this in javascript to check first (i set the strings for effect, i normally just use a bool or similiar):

function checkEndian(){
    var a = new ArrayBuffer(4);
    var b = new Uint8Array(a);
    var c = new Uint32Array(a);
    b[0] = 0xa1;
    b[1] = 0xb2;
    b[2] = 0xc3;
    b[3] = 0xd4;
    if(c[0] == 0xd4c3b2a1) return "little endian";
    if(c[0] == 0xa1b2c3d4) return "big endian";
    else throw new Error("Something crazy just happened"); 
}
Ryan
  • 2,755
  • 16
  • 30