Search code examples
javascripthexasciinode-red

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!


Solution

  • 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.