2

I know you can get an arraybuffer from an XMLHttpRequest in JavaScript.

var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var byteArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteArray.byteLength; i++) {
      // do something with each byte in the array
    }
  }
};

oReq.send(null);

Is there a way to simply inline into the JavaScript source code an array buffer? Something like this:

var buffer = new ArrayBuffer([
  1, 5, 32, 31, ...
])

I won't be able to assume a Uint8Array structure, the array buffer data will consist of 3-bit, 4-bit, etc., sequences, so ideally there would be some way to create an array buffer inline, maybe even:

var buffer = new ArrayBuffer('1010101011110000011001101010101011011000')...

Does anything like this exist, or is XMLHttpRequest the only way to do this in the browser?

4
  • 1
    It seems pretty hard to make buffers work with plain bits in js. It might be impossible. I'll research a bit more, but it seems like the number of bits you use in buffer data has to be, exclusively, a multiple of eight. Commented Sep 7, 2020 at 0:41
  • For anyone wondering why 8 bit is the lowest you can go: There is no performance gain from going any lower. Commented Sep 7, 2020 at 2:07
  • It's unclear what you mean by "I won't be able to assume a Uint8Array structure, the array buffer data will consist of 3-bit, 4-bit, etc., sequence". Where does the data that you want to inline come from, and how would it not be whole bytes? Commented Sep 7, 2020 at 2:26
  • Does this answer your question? Create ArrayBuffer from Array (holding integers) and back again Commented Sep 7, 2020 at 3:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.