Converting ArrayBuffer to int in Javascript

Andrew Simpson picture Andrew Simpson · Jul 4, 2015 · Viewed 11.2k times · Source

I am trying to convert an ArrayBuffer to an int using JavaScript. My app uses WebSocket and on the Sender side I have an integer between 0 and 4. I convert this ArraySegment in C#. I send this via web sockets to my JavaScript client which receives it as an ArrayBuffer.

The ArrayBuffer now holds the value of 0 or 1 or 2 or 3. How can I 'read' that value?

Answer

stdob-- picture stdob-- · Jul 4, 2015

Use DataView:

var buffer = new ArrayBuffer(16);
var dv = new DataView(buffer, 0);

dv.setInt16(1, 42);
dv.getInt16(1); //42