简体   繁体   中英

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

  • 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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM