Node.js 中缓冲区的二进制字符串
String of Binary to Buffer in Node.js
我试图通过将字符流解析为 UTF-16 编码,将 0
和 1
的字符串转换为等效的 Buffer
。
例如:
var binary = "01010101010101000100010"
其结果将是以下缓冲区
<Buffer 55 54>
请注意 Buffer.from(string, "binary")
无效,因为它创建了一个缓冲区,其中每个单独的 0
或 1
都被解析为它自己的拉丁文单字节编码字符串。来自 Node.js 文档:
'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'.
- 使用“.match”查找所有 16 位组。
- 使用 parseInt
将二进制字符串转换为数字
- 创建 Uint16Array 并将其转换为 Buffer
在节点 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"))
我试图通过将字符流解析为 UTF-16 编码,将 0
和 1
的字符串转换为等效的 Buffer
。
例如:
var binary = "01010101010101000100010"
其结果将是以下缓冲区
<Buffer 55 54>
请注意 Buffer.from(string, "binary")
无效,因为它创建了一个缓冲区,其中每个单独的 0
或 1
都被解析为它自己的拉丁文单字节编码字符串。来自 Node.js 文档:
'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'.
- 使用“.match”查找所有 16 位组。
- 使用 parseInt 将二进制字符串转换为数字
- 创建 Uint16Array 并将其转换为 Buffer
在节点 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"))