gpt4 book ai didi

javascript - 如何将 ArrayBuffer 填充为 4 的倍数?

转载 作者:搜寻专家 更新时间:2023-11-01 04:25:30 24 4
gpt4 key购买 nike

我正在使用新的 FileReader API 以 ArrayBuffer 的形式读入文件.然后我通过 UInt32Array 在 ArrayBuffer 中创建一个“ View ”与另一个 API 一起工作。

问题是我的文件不一定是 4 字节的倍数,当我尝试向 Uint32Array 提供错误时,Chrome 会抛出错误(“Uncaught RangeError: bofyshould be a multiple ofe”)多。那么如何用 0 填充 ArrayBuffer 使其变成倍数呢?

var reader = new FileReader();
var pos = 0;
var xxh = XXH();

reader.onprogress = function(progress) {
// round down length to the nearest multiple of 4, save the remaining bytes for the next iteration
var length = Math.floor((progress.loaded - pos)/Uint32Array.BYTES_PER_ELEMENT);
var arr = new Uint32Array(reader.result, pos, length);
pos += length * Uint32Array.BYTES_PER_ELEMENT;
xxh.update(arr);
};

reader.onload = function() {
// `pos` will be a multiple of 4 here but the number of remaining bytes might not be. How can I pad `reader.result`?
var arr = new Uint32Array(reader.result, pos); // error occurs here
xxh.update(arr);
};

reader.readAsArrayBuffer(file);

最佳答案

改用 Uint8Array,因为它具有字节精度。如果您需要访问除无符号字节以外的其他类型的数据,请创建一个 DataView :new DataView(arr.buffer)

reader.onprogress = function(progress) {
var arr = new Uint8Array(reader.result, pos, length);
xxh.update(arr);
};

reader.onload = function() {
var arr = new Uint8Array(reader.result, pos);
xxh.update(arr);
};

关于javascript - 如何将 ArrayBuffer 填充为 4 的倍数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20919525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com