简体   繁体   English

将包含ASCII二进制十六进制的字符串转换为Buffer

[英]Convert string containing binary hex in ASCII into Buffer

I am using node.js. 我正在使用node.js.

I have this string msg_str with the following contents "0102ab00aabb00" . 我有这个字符串msg_str与以下内容"0102ab00aabb00" I want to convert this string content (ASCII representing binary hex) and store it into a Buffer such that the contents of the Buffer looks like <01 02 ab 00 aa bb 00 > . 我想转换此字符串内容(表示二进制十六进制的ASCII)并将其存储到缓冲区中,以使缓冲区的内容看起来像<01 02 ab 00 aa bb 00 >

Some preliminary code I wrote which does not work as expected; 我写的一些初步代码没有按预期工作;

msg_str = "0102ab00aabb00";
buffer_binary = new Buffer(msg_str);
console.log(msg_str);   
console.log(buffer_binary); 

The console output of buffer_binary is 30 31 30 32 61 62 30 30 61 61 62 62 30 30 . buffer_binary的控制台输出是30 31 30 32 61 62 30 30 61 61 62 62 30 30 The correct output should be 01 02 ab 00 aa bb 00 . 正确的输出应为01 02 ab 00 aa bb 00

You need to tell the Buffer constructor that your string is in hex. 您需要告诉Buffer构造函数您的字符串是否为十六进制。 Fortunately, this is pretty easy :) 幸运的是,这很容易:)

msg_str = "0102ab00aabb00";
buffer_binary = new Buffer(msg_str, "hex"); // specify hex
console.log(msg_str); // logs 0102ab00aabb00
console.log(buffer_binary); // logs <Buffer 01 02 ab 00 aa bb 00>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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