7

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?

08Dc91wk
  • 4,254
  • 8
  • 34
  • 67
Andrew Simpson
  • 6,883
  • 11
  • 79
  • 179

2 Answers2

11

Use DataView:

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

dv.setInt16(1, 42);
dv.getInt16(1); //42
stdob--
  • 28,222
  • 5
  • 58
  • 73
  • Is this base zero or starts from 1 as you have in your example? – Andrew Simpson Jul 04 '15 at 11:02
  • I use this: var dv = new DataView(e.Data); var index = dv.getInt16(1); but all I get is zero? I know (for testing I am passing a '3')? – Andrew Simpson Jul 04 '15 at 11:06
  • In DataView constructor offset relatively to ArrayBuffer, in `setInt16` or `getInt16` relatively to DataView. – stdob-- Jul 04 '15 at 11:13
  • yes, that is what I tried. So, my ArrayBuffer is say 1000 length in bytes. I just want to read the very 1st byte as an integer? ( have said in my code myArray[0]=(byte)3 you see – Andrew Simpson Jul 04 '15 at 11:15
  • Ok, let try `getInt8(0)` instead `getInt16(0)`? – stdob-- Jul 04 '15 at 11:25
  • Will try, but need to reboot pc 1st :) – Andrew Simpson Jul 04 '15 at 11:30
  • @stdob-- The second param to setInt16, why are you passing 42? I have been looking at the docs and cannot figure out what is supposed to be passed there – YourGoodFriend Jul 31 '18 at 15:27
  • @YourGoodFriend This is just an example. It can be either 42, or another number - for example 32767 )) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setInt16 – stdob-- Jul 31 '18 at 20:34
1
var i = new Uint8Array(buf)[0];

Then i is what you need. If you need subarray():

ArrayBuffer.prototype.subarray = function (a, b) {
    var u = new Uint8Array(this);
    return new Uint8Array(u.subarray(a, b)).buffer;;
};

and

var i = new Uint8Array(buf.subarray(0,1))[0];
Wilson Luniz
  • 459
  • 2
  • 7
  • 18