Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Uint8Array, Uint16Array, Uin32Array

Tags:

javascript

I recently just started using webgland I am trying to understand the difference between Uint8Array, Uint16Array, Uin32Array. and how you would use them. I found some information about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array but can anyone tell me the difference between them and how you would use them?

like image 255
shell Avatar asked Aug 02 '16 10:08

shell


People also ask

What is Uint8Array used for?

The Uint8Array() constructor creates a typed 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).

How do you concatenate Uint8Array?

You can use the set method. Create a new typed array with all the sizes. Example: var arrayOne = new Uint8Array([2,4,8]); var arrayTwo = new Uint8Array([16,32,64]); var mergedArray = new Uint8Array(arrayOne.

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

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


1 Answers

Uint***Arrays construct non-typed arrays (commented by @zfor, so, for example, push would be undefined) with numbers only (still bytes). The difference is that each constructor array has different byte range in memory. Uint8Array has 1 byte only, then the limit of a number is 255. Uint16Array is 2 bytes long, then the limit is 65535. Uint32Array is 4 bytes long, so the limit is 4294967295.

When constructing a Uint*Array you declare the array length as the first argument:

var arr = new Uint8Array(1);

If you declare a array/buffer/object instead, the constructor still proccess them as a Uint*Array.

var arr = new Uint8Array([10, 257]);
console.log(arr[0]); // 10
console.log(arr[1]); // 1 (same thing: 257 % 256)

Now, see some examples:

arr[0] = 256;
console.log(arr[0]); // 0

arr[0] = 255;
console.log(arr[0]); // 255
like image 152
Klaider Avatar answered Sep 18 '22 00:09

Klaider