Uint8Array to ArrayBuffer

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?



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

var arrayBuffer = foobar.buffer; 

just this! And it works for me!


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)

If you need to convert it back into an ArrayBuffer(), you need to add each value manually.

That means, you need to cycle through each one of them, one by one.

Probably the fastest way will be like this:

var buffer = new ArrayBuffer(foobar.length);

foobar.map(function(value, i){buffer[i] = value});


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.