[node.js] nodejs 원시 버퍼 데이터를 16 진수 문자열로 표시하는 방법

다음 코드는 SerialPort 모듈을 사용하여 블루투스 연결에서 데이터를 수신합니다.

콘솔에 16 진수 형식의 데이터 스트림이 인쇄 될 것으로 예상하고 있습니다. 그러나 콘솔은 이상한 심볼을 보여줍니다. 콘솔에서 데이터를 디코딩하고 표시하는 방법을 알고 싶습니다.

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



답변

이 코드는 데이터 버퍼를 16 진수 문자열로 표시합니다.

buff.toString('hex');


답변

가장 간단한 방법은 최고의 답변입니다.

대체 방법 :

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


답변