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?
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".
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.
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.
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.
Use DataView:
var buffer = new ArrayBuffer(16);
var dv = new DataView(buffer, 0);
dv.setInt16(1, 42);
dv.getInt16(1); //42
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With