Convert decimal to hex and back after transformation

I want to do the following.

msg.payload[8]=12
msg.payload[9]=39161

I want to convert msg.payload[8] and [9] to Hex numbers (respectively C and 98F9).

I have several issues.

  1. how do I convert to Hex numbers
  2. how do I convert from Hex to decimal. I tried
    var HexNumber = 'C98F9';
    msg.payload = parseInt(HexNumber);
    return msg;
    But that resulted in NaN

0xF will result in 15

I'm a newbie in Node-Red, any help is appreciated.


John

When you say you want to convert it to a hex number, do you mean that you want a string containing "98f9"? If you are not sure what that means then tell us what do you want to do with the hex number.

I want to convert both payloads to Hex and then combine both Hex numbers and convert to a decimal number

So If I can convert the payloads to Hex (resulting in C and 98FG) and combine these strings (resulting in C98FG) it is ok. After that the string containing the Hex number should be converted to a decimal value (end result 825593).


John

You don't need to convert it at all, just shift the first value left 16 bits and add on the second

msg.payload = (msg.payload[8] <<16) + (msg.payload[9] & 0xffff)
return msg

The and with 0xffff is to force it to an unsigned value, as, for example, if the second word was -1 it would actually mean 65535

Thanks a lot, this is much simpler as in C++.


John