Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Uint8Array to Array in Javascript

I have Uint8Array instance that contains binary data of some file.
I want to send data to the server, where it will be deserialized as byte[].
But if I send Uint8Array, I have deserialization error.

So, I want to convert it to Array, as Array is deserialized well.
I do it as follows:

    function uint8ArrayToArray(uint8Array) {         var array = [];          for (var i = 0; i < uint8Array.byteLength; i++) {             array[i] = uint8Array[i];         }          return array;     } 

This function works fine, but it is not very efficient for big files.

Question: Is there more efficient way to convert Uint8Array --> Array?

like image 462
Kysil Ivan Avatar asked Apr 16 '15 13:04

Kysil Ivan


People also ask

Is Uint8Array an array buffer?

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

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.

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


1 Answers

You can use the following in environments that support Array.from already (ES6)

var array = Array.from(uint8Array) 

When that is not supported you can use

var array = [].slice.call(uint8Array) 
like image 108
darthmaim Avatar answered Sep 20 '22 03:09

darthmaim