1

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?

Lance
  • 75,200
  • 93
  • 289
  • 503
  • 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. – JUAN FELIPE SUÁREZ BURGOS Sep 07 '20 at 00:41
  • For anyone wondering why 8 bit is the lowest you can go: There is no performance gain from going any lower. – GirkovArpa Sep 07 '20 at 02: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? – Bergi Sep 07 '20 at 02:26
  • Does this answer your question? [Create ArrayBuffer from Array (holding integers) and back again](https://stackoverflow.com/questions/34089569/create-arraybuffer-from-array-holding-integers-and-back-again) – kmoser Sep 07 '20 at 03:10

0 Answers0