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

时间:2014-01-04 10:05:50

标签: javascript

我正在使用新的FileReader API将文件作为ArrayBuffer读入。然后,我通过UInt32Array在ArrayBuffer中创建一个“视图”,以使用另一个API。

问题是我的文件不一定是4个字节的倍数,当我尝试向Uint32Array提供错误的倍数时,Chrome会抛出错误(“未捕获的RangeError:bofys应该是多个”)。那么如何用{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);

1 个答案:

答案 0 :(得分:2)

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