bren
bren

Reputation: 4334

String of Binary to Buffer in Node.js

I'm trying to convert a string of 0 and 1 into the equivalent Buffer by parsing the character stream as a UTF-16 encoding.

For example:

var binary = "01010101010101000100010"

The result of that would be the following Buffer

<Buffer 55 54>

Please note Buffer.from(string, "binary") is not valid as it creates a buffer where each individual 0 or 1 is parsed as it's own Latin One-Byte encoded string. From the Node.js documentation:

'latin1': A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC 1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes).

'binary': Alias for 'latin1'.

Upvotes: 5

Views: 3239

Answers (1)

sney2002
sney2002

Reputation: 896

  • Use "".match to find all the groups of 16 bits.
  • Convert the binary string to number using parseInt
  • Create an Uint16Array and convert it to a Buffer

Tested on node 10.x

function binaryStringToBuffer(string) {
    const groups = string.match(/[01]{16}/g);
    const numbers = groups.map(binary => parseInt(binary, 2))

    return Buffer.from(new Uint16Array(numbers).buffer);
}

console.log(binaryStringToBuffer("01010101010101000100010"))

Upvotes: 6

Related Questions