Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ArrayBuffer to int in Javascript

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?

like image 362
Andrew Simpson Avatar asked Jul 04 '15 10:07

Andrew Simpson


People also ask

What is ArrayBuffer in Javascript?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".

Is Uint8Array same as ArrayBuffer?

Uint8Array – treats each byte in ArrayBuffer as a separate number, with possible values from 0 to 255 (a byte is 8-bit, so it can hold only that much). Such value is called a “8-bit unsigned integer”. Uint16Array – treats every 2 bytes as an integer, with possible values from 0 to 65535.

What is the difference between a buffer and an ArrayBuffer?

Generally speaking: Buffers store an array of unformatted memory. An array is a general term of contiguous memory. A buffer needs to be bound to the context, whereas an array is just an array of data.

What is Uint8Array used for?

The Uint8Array. from() method is used to create a new Uint8Array from an array-like or iterable object. So when you want to convert an arrayLike or iterable object then you can be used this function by passing the object as a parameter to this function along with map function and value used for map function if needed.


2 Answers

Use DataView:

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

dv.setInt16(1, 42);
dv.getInt16(1); //42
like image 123
stdob-- Avatar answered Oct 17 '22 03:10

stdob--


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];
like image 1
Wilson Luniz Avatar answered Oct 17 '22 03:10

Wilson Luniz