Java put/putShort with JS

Tags: ,



Can someone tell me the equivalent of java put and putShort in JavaScript ?

Answer

I think what you are looking for is first:

  • create the array buffer:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer

  • then use a data view to get and set into it:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView

In dataview you can control the byte ordering (big/little endian)

And here is an example, getting binary representation of NaN in JS https://jsfiddle.net/ibowankenobi/h2r5ybfp/

!function(){
    var ab = new ArrayBuffer(8),
        dv = new DataView(ab);
  dv.setFloat64(0,NaN,false); //big endian by default
  document.body.textContent = Array.apply(null,Array(8))
    .map(function(d,i){
       return ("00000000" + dv.getUint8(i).toString(2)).slice(-8)
    }).join(" ");
}();


Source: stackoverflow