Javascript 如何将阵列缓冲区填充为4的倍数?
我正在使用新的FileReaderAPI将文件作为。然后,我通过在ArrayBuffer中创建一个“视图”来使用另一个API 问题是,我的文件不一定是4字节的倍数,当我尝试输入Javascript 如何将阵列缓冲区填充为4的倍数?,javascript,Javascript,我正在使用新的FileReaderAPI将文件作为。然后,我通过在ArrayBuffer中创建一个“视图”来使用另一个API 问题是,我的文件不一定是4字节的倍数,当我尝试输入uint32数组时,Chrome会抛出一个错误(“uncaughtrangeerror:bofy应该是ofe的倍数”)。那么,如何用0填充数组缓冲区,使其成为倍数 var reader = new FileReader(); var pos = 0; var xxh = XXH(); reader.onprogress
uint32数组时,Chrome会抛出一个错误(“uncaughtrangeerror:bofy应该是ofe的倍数”)。那么,如何用0填充数组缓冲区
,使其成为倍数
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,因为它具有字节精度。如果需要使用非无符号字节的其他类型访问数据,请创建一个数据视图:newdataview(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);
};