Willem
Willem

Reputation: 1102

What is the best practice to make JavaScript's Typed Arrays "Endian Safe"?

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?

Upvotes: 1

Views: 448

Answers (2)

Ryan
Ryan

Reputation: 2815

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"); 
}

Upvotes: 1

lostsource
lostsource

Reputation: 21830

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

Upvotes: 1

Related Questions