136

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
  • 13
    data is already a buffer, no need to convert. Then: data.toString('hex'); Commented Sep 18, 2013 at 18:42

2 Answers 2

297

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

buff.toString('hex');
Sign up to request clarification or add additional context in comments.

4 Comments

do u know how to do the reverse?
bubakazouba: new Buffer( buf.toString('hex'), 'hex' );
[DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. So now it should be Buffer.from( buf.toString('hex'),'hex');
It returns for me [object ArrayBuffer]? what's wrong?
3

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

1 Comment

This answer was actually useful for me, because I have to join it with '-' for it to interop with C#. Upvoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.