Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad an ArrayBuffer to a multiple of 4?

Tags:

javascript

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);
like image 543
mpen Avatar asked Jan 04 '14 10:01

mpen


People also ask

Is ArrayBuffer a binary?

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.

What is the point of ArrayBuffer?

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.

What is a ArrayBuffer?

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".

What is a TypedArray?

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.


1 Answers

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);
};
like image 136
Juan Garcia Avatar answered Sep 21 '22 09:09

Juan Garcia