Javascript Uint8Array 到 ArrayBuffer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37228285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uint8Array to ArrayBuffer
提问by Lao Tzu
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.
所以我有一个 ArrayBuffer,它是我用新的 HTML5 文件阅读器作为 ArrayBuffer() 读取的文件的文件内容,我可以通过执行以下操作将 ArrayBuffer 转换为 Uint8Array。
//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?
我如何将最后一个过程反转回 ab?
Here is the kind of output I am getting after decryption: http://prntscr.com/b3zlxr
这是我解密后得到的输出类型:http: //prntscr.com/b3zlxr
What kind of format is this, and how do I get it into blob?
这是一种什么样的格式,我如何把它变成 blob?
回答by kuokongqingyun
I found a more simple method to get the ArrayBuffer of Uint8Array.
我找到了一个更简单的方法来获取Uint8Array的ArrayBuffer。
var arrayBuffer = foobar.buffer;
just this! And it works for me!
只是这个!它对我有用!
回答by Stéphane
With kuokongqingyun option, it will not always work, because the buffer may be bigger than the data view.
使用 kuokongqingyun 选项,它不会总是有效,因为缓冲区可能比数据视图大。
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
当使用array.buffer
它的重要用途byteOffset
,并byteLength
计算实际数据
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)
}
回答by Ismael Miguel
If you need to convert it back into an ArrayBuffer()
, you need to add each value manually.
如果需要将其转换回ArrayBuffer()
,则需要手动添加每个值。
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});