Why is Javascript TypeDArray not working?

457 views Asked by At

I have 4 bytes ArrayBuffer and I assigned a number at the index 0 using dataview. When I try to get the value using dataview that gives result correctly but it does not give correct result when I try to get value using typed array. Can anyone help on this? Here are the code:

var buffer = new ArrayBuffer(4);
var dataview = new DataView(buffer);
dataview.setUint32(0,5000);

var unint32 = new Uint32Array(buffer);

console.log(unint32[0]); //2282946560 instead of 5000
console.log(dataview.getUint32(0)); //shows correctly 5000
1

There are 1 answers

1
MaxArt On BEST ANSWER

That's because you're using the wrong endian-type when using setUint32. Specifically, you need it to store a little-endian representation, because your hardware behaves like that.

You can see this more easily using hexadecimal values. Now, 5000 === 0x1388, while 2282946560 = 0x88130000. Can you see the pattern here?

Try this instead:

dataview.setUint32(0, 5000, true);

var unint32 = new Uint32Array(buffer);

console.log(unint32[0]); // 5000, yay!

As apsillers pointed out, if you're going to use dataview to retrieve the value too, you'll also have to use dataview.getUint32(0, true).

As a last word, if you just need to work with Uint32 numbers, forget about the DataView and use the typed array right away:

var buffer = new ArrayBuffer(4);
var unint32 = new Uint32Array(buffer);
unint32[0] = 5000;

You'll never get it wrong with this.

On the other hand, if you need to fill an ArrayBuffer with raw binary data, you'd like to check then endiannes of your hardware with this little trick.