Search code examples
javascriptcryptographysha256arraybuffer

How do I turn an Array of Bits as Strings into an ArrayBuffer


Let's say I have an array of 256 character/strings that are either "1" or "0"

So something like

["1","1","0","0","1","0", ...]

I need to turn this in an ArrayBuffer (The individuals bits are a SHA-256 hash)

What is the easiest way to fill the 32 byte ArrayBuffer, with each from the array.


Solution

  • You can use join, to join 8 bits together, and then use parseInt with 2 as the radix to convert the binary number, and then place in the arrayBuffer.

    Below is an example.

    //lets make some demo data.
    const data = new Array(256).fill().map(m => Math.random() < 0.5 ? '1' : '0');
    
    //convert data of '0', '1' into ArrayBuffer
    const buffer = new Uint8Array(32);
    let bpos = 0;
    for (let l = 0; l < data.length; l += 8) {
      const b = data.slice(l, l + 8).join(''); 
      buffer[bpos] = parseInt(b, 2);
      bpos += 1;
    }
    
    console.log(buffer);