0

I have a binary string and I need to be able to convert it to an ArrayBuffer/TypedArray containing the 0-255 values of each octet. For example:

const string = "01110100011001010111100001110100";

// should log an ArrayBuffer containing 116, 101, 120, and 116
console.log(stringToArrayBuffer(string));

My question is basically the reverse of this question.

luek baja
  • 1,475
  • 8
  • 20

1 Answers1

0

A simple loop with parseInt(val, 2) should do it:

function stringToArrayBuffer(str) {
  const arr = new Uint8Array(str.length / 8);
  for(let i = 0; i<str.length; i+=8) {
    arr[i/8] = parseInt(str.slice(i, i+8), 2);
  }
  return arr;
}
const string = "01110100011001010111100001110100";

// should log an ArrayBuffer containing 16, 101, 120, and 116
console.log(stringToArrayBuffer(string));
Kaiido
  • 123,334
  • 13
  • 219
  • 285