9

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?

6

2 Answers 2

11

Use DataView:

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

dv.setInt16(1, 42);
dv.getInt16(1); //42
Sign up to request clarification or add additional context in comments.

8 Comments

Is this base zero or starts from 1 as you have in your example?
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')?
In DataView constructor offset relatively to ArrayBuffer, in setInt16 or getInt16 relatively to DataView.
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
Ok, let try getInt8(0) instead getInt16(0)?
|
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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.