Lao Tzu
Lao Tzu

Reputation: 909

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?

Upvotes: 75

Views: 89279

Answers (5)

Randall Flagg
Randall Flagg

Reputation: 5108

Although this was the question that came every time when I searched for the answer to my problem (getting a Buffer object and not an ArrayBuffer) and this is not exactly what was asked and after I reviewed all the answers here this is what I did at the end:

Buffer.from(file.buffer,0,file.buffer.length);

Upvotes: 3

Stéphane
Stéphane

Reputation: 1789

Just using .buffer 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)
}

Upvotes: 88

Jelle Hak
Jelle Hak

Reputation: 499

The buffer property of a TypedArray is an ArrayBuffer

new Uint8Array(4).buffer // ArrayBuffer(4)

Upvotes: 2

kuokongqingyun
kuokongqingyun

Reputation: 1060

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

var arrayBuffer = foobar.buffer; 

just this! And it works for me!

Upvotes: 83

Ismael Miguel
Ismael Miguel

Reputation: 4241

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});

Upvotes: -1

Related Questions