3

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

Community
  • 1
  • 1
bren
  • 4,176
  • 3
  • 28
  • 43
  • You could generate a HEX string from that ([here is an example](https://stackoverflow.com/questions/17204912/javascript-need-functions-to-convert-a-string-containing-binary-to-hex-then-co)) and use `Buffer.from(hexStr, "hex")`. By the way, your example is wrong, `0101010101010100` is `5554`, you have 7 extra bits in there. – Titus Jan 24 '20 at 02:46

1 Answers1

4
  • 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"))
sney2002
  • 856
  • 3
  • 6