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

0

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

Comments

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.