dataview - Why is Javascript TypeDArray not working? -


i have 4 bytes arraybuffer , assigned number @ index 0 using dataview. when try value using dataview gives result correctly not give correct result when try value using typed array. can on this? here 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 

that's because you're using wrong endian-type when using setuint32. specifically, need store little-endian representation, because hardware behaves that.

you can see more using hexadecimal values. now, 5000 === 0x1388, while 2282946560 = 0x88130000. can see pattern here?

try 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 use dataview retrieve value too, you'll have use dataview.getuint32(0, true).

as last word, if need work uint32 numbers, forget dataview , use typed array right away:

var buffer = new arraybuffer(4); var unint32 = new uint32array(buffer); unint32[0] = 5000; 

you'll never wrong this.

on other hand, if need fill arraybuffer raw binary data, you'd check endiannes of hardware this little trick.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -