Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uint32Array( buffer, byteOffset, length ) does not work as expected

According to MSDN I can create a Uint32Array in 3 ways:

  1. new Uint32Array( length );
  2. new Uint32Array( array );
  3. new Uint32Array( buffer, byteOffset, length );

First and second method work great, but third didn't work for me. What's wrong in this code?

var buffer = new ArrayBuffer(8);
var uint32s = new Uint32Array(buffer, 4, 4);
uint32s[0] = 0x05050505;
var uint8s = new Uint8Array(buffer);
for (var i =0; i< 8; i++)
{
    alert(uint8s[i]);
}

This works fine, but of course byteOffset = 0.

var uint32s = new Uint32Array(buffer);
like image 428
Demion Avatar asked Dec 07 '11 17:12

Demion


People also ask

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 Uint8Array?

The Uint8Array typed array represents an array of 8-bit unsigned integers. The contents are initialized to 0 . Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

What is Uint32Array?

The Uint32Array typed array represents an array of 32-bit unsigned integers in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0 .

What is ArrayBuffer in Nodejs?

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".


1 Answers

It seems that the documentation is incorrect here in that length is not a number of bytes but the number of 32-bit integers that the Uint32Array will contain.

Exhibit A

Changing the code to var uint32s = new Uint32Array(buffer, 4, 1); works.

Exhibit B

The documentation for Uint32Array on MDN says that length is a count of items, not bytes.

Exhibit C

It doesn't really make sense to have the constructor accept a length in bytes. What should happen if length is not a multiple of 4?

like image 80
Jon Avatar answered Sep 30 '22 03:09

Jon