如何将 nodejs 原始缓冲区数据显示为十六进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18879880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display nodejs raw Buffer data as Hex string
提问by GingerJim
The following code uses SerialPort module to listen to data from a bluetooth connection.
以下代码使用 SerialPort 模块来侦听来自蓝牙连接的数据。
I am expecting to see a stream of data in Hexadecimal format printed in console. But the console just shows some weird simbols. I want to know how can I decode and display the data in console.
我期待在控制台中看到十六进制格式的数据流。但是控制台只显示一些奇怪的符号。我想知道如何在控制台中解码和显示数据。
var serialPort = new SerialPort("/dev/tty.EV3-SerialPort", {
parser: SP.parsers.raw
}, false); // this is the openImmediately flag [default is true]
serialPort.open(function () {
console.log('open');
serialPort.on('data', function(data) {
var buff = new Buffer(data, 'utf8'); //no sure about this
console.log('data received: ' + buff.toString());
});
});
回答by Seryh
This code will show the data buffer as a hex string:
此代码将数据缓冲区显示为十六进制字符串:
buff.toString('hex');
回答by Omar Taylor
Top answer is the simplest way to do it.
最佳答案是最简单的方法。
An alternative method:
另一种方法:
data = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
Array.prototype.map.call(new Uint8Array(data),
x => ('00' + x.toString(16)).slice(-2))
.join('').match(/[a-fA-F0-9]{2}/g).reverse().join('');

