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