5

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

1
  • You could generate a HEX string from that (here is an example) and use Buffer.from(hexStr, "hex"). By the way, your example is wrong, 0101010101010100 is 5554, you have 7 extra bits in there. Commented Jan 24, 2020 at 2:46

1 Answer 1

6
  • 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"))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.