I'm using the new FileReader API to read in a file as an ArrayBuffer. I then create a "view" into that ArrayBuffer via UInt32Array to work with another API.
The problem is that my files aren't necessarily multiples of 4 bytes, and Chrome throws an error ("Uncaught RangeError: bofyshould be a multiple ofe") when I try to feed Uint32Array
a bad multiple. So how can I pad the ArrayBuffer
with 0s so that it becomes a multiple?
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);
The basic binary object is ArrayBuffer – a reference to a fixed-length contiguous memory area. This allocates a contiguous memory area of 16 bytes and pre-fills it with zeroes.
Basically ArrayBuffer is used to keep binary data. It can be the binary data of an image for example. In other languages buffers are proved very useful.
The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".
A TypedArray object describes an array-like view of an underlying binary data buffer. There is no global property named TypedArray , nor is there a directly visible TypedArray constructor.
Use Uint8Array instead, as it have byte precision. If you need to access the data with other types different than unsigned byte, create a 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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With