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});
Some answers here will only work if the internal buffer of your Uint8Array has no offset. The answers using .slice() will make an expensive memory copy that is not always needed.
The easiest and most efficient way is like this :
var buffer = new ArrayBuffer(foobar.buffer, foobar.byteOffset, foobar.byteLength);
Example :
let data = Uint8Array.from([1,2,3,4])
let foobar = data.subarray(1,3) // [2, 3]
console.log(new Uint8Array(foobar.buffer, foobar.bytesOffset, foobar.byteLength).toString()) // will print [2, 3]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.