Bart
Bart

Reputation: 35

Hex to ascii wrong conversion

I have got a javascript function to convert from HEX to ASCII and then output that to a serial connection. However when monitoring the serial connection, I can see that the converted output is not correct.

I have this javascript code:

function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
    str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
return {payload: hex2a(msg.payload)}; // returns '2460'

As an example, i want to convert this HEX :

0340209c

BUT, when monitoring the serial connection i see that what gets actually sent is this:

03 40 20 c2 9c  

So the device answers with a fault message. I'm scratching my head here. Some hex commands do convert correctly ( 0340615b , for example). I'm outputting to the serial connection via node-red. The output node only seems to accept ascii text and not HEX.

I hope someone can guide me in the right direction. Thank you for any reply!

Upvotes: 1

Views: 4169

Answers (4)

gus
gus

Reputation: 27

Try this:

function toAscii(hex, delimiter) {
  var outputstr = '';
  inputstr = inputstr.replace(/^(0x)?/g, '');
  inputstr = inputstr.replace(/[^A-Fa-f0-9]/g, '');
  inputstr = inputstr.split('');
  for(var i=0; i<inputstr.length; i+=2) outputstr += String.fromCharCode(parseInt(inputstr[i]+''+inputstr[i+1], 16));
  return outputstr;
} 

Upvotes: 0

chovy
chovy

Reputation: 75774

Convert hex to ascii in Node.js (tested in v5+)

const hex = '...';
const ascii = new Buffer(hex, 'hex');

https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings

Upvotes: 0

Bart
Bart

Reputation: 35

Thx! @Metabolix for pointing me in the right direction!! I have solved my problem by converting my HEX string to a buffer with the following code.

return {payload: new Buffer(msg.payload, "hex")};

The msg.payload is an injected string like:

0340209c

While monitoring the serial connection, it now reads the correct command!

Upvotes: 1

Metabolix
Metabolix

Reputation: 186

This happens because JavaScript and Node-RED use the UTF-8 encoding for text, where the Unicode character number U+009c is encoded as c2 9c. (Please note that ASCII is actually a 7-bit character set from 0x00 to 0x7f, and the 8-bit codes from 0x80 to 0xff depend on the charset or encoding.)

Node-RED has also binary support (see this GitHub issue). The documentation is rather vague, but looks like you should use a Node.js Buffer object as the payload.

Upvotes: 0

Related Questions