How to display nodejs raw Buffer data as Hex string

丶灬走出姿态 提交于 2019-12-29 11:40:48

问题


The following code uses SerialPort module to listen to data from a bluetooth connection.

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());
 });  
});

回答1:


This code will show the data buffer as a hex string:

buff.toString('hex');



回答2:


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('');


来源:https://stackoverflow.com/questions/18879880/how-to-display-nodejs-raw-buffer-data-as-hex-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!