Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uint8Array to ArrayBuffer

Tags:

javascript

So I have a ArrayBuffer which is of the file contents of a file which I read with the new HTML5 file reader as ArrayBuffer(), and I can convert the ArrayBuffer to Uint8Array by doing the following.

//ab = established and defined ArrayBuffer  var foobar = new Uint8Array([ab]);  //var reversed = reverseUint8Array(foobar);   //reversed should equal ab  

How do I reverse that last process back into ab?

Here is the kind of output I am getting after decryption: http://prntscr.com/b3zlxr

What kind of format is this, and how do I get it into blob?

like image 837
Lao Tzu Avatar asked May 14 '16 15:05

Lao Tzu


People also ask

Is Uint8Array an ArrayBuffer?

For instance: 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.

Is ArrayBuffer same as buffer?

1. A Buffer is just a view for looking into an ArrayBuffer . A Buffer , in fact, is a FastBuffer , which extends (inherits from) Uint8Array , which is an octet-unit view (“partial accessor”) of the actual memory, an ArrayBuffer .

How do I merge 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 new Uint8Array?

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


2 Answers

I found a more simple method to get the ArrayBuffer of Uint8Array.

var arrayBuffer = foobar.buffer;  

just this! And it works for me!

like image 70
kuokongqingyun Avatar answered Sep 20 '22 05:09

kuokongqingyun


With kuokongqingyun option, it will not always work, because the buffer may be bigger than the data view.

See this example:

let data = Uint8Array.from([1,2,3,4]) var foobar = data.subarray(0,2) var arrayBuffer = foobar.buffer;   console.log(new Uint8Array(arrayBuffer)) // will print [1,2,3,4] but we want [1,2] 

When using array.buffer it's important use byteOffset and byteLength to compute the actual data

let data = Uint8Array.from([1,2,3,4]) var foobar = data.subarray(0,2) var arrayBuffer = foobar.buffer.slice(foobar.byteOffset, foobar.byteLength + foobar.byteOffset);   console.log(new Uint8Array(arrayBuffer)) // OK it now prints [1,2] 

So here is the function you need:

function typedArrayToBuffer(array: Uint8Array): ArrayBuffer {     return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset) } 
like image 28
Stéphane Avatar answered Sep 23 '22 05:09

Stéphane