Converting Decimal to Hex

const hexchars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
let val = msg.payload;
let answer = "";
let size = 2;
while (size--) {
    answer = hexchars[val & 0xF] + answer;
    val = val >> 4;
}
msg.payload = "0x" + answer;
return msg;

i see Apologies again :sweat_smile:

damn you did that pretty fast :sweat_smile: Would it be to much to ask you to explain how your code works, if so ill go do the research myself I don't mind was just wondering

Upfront info to keep in mind / refer back to...

  • & is a Bitwise AND
  • & 0xF means AND the value with 0xf (or decimal 15 or binary 0000 1111)
  • >> is a Sign-propagating right shift
  • >> 4 means shift the bits in a number 4 to right - effectively dropping the right most digit & moving other digits in the number to the right

Example of &

  • 201 in binary is 1100 1001
  • 0xF in binary is 0000 1111
  • 1100 1001 AND 0000 1111 == 0000 1001 == 9

The routine...

answer = hexchars[val & 0xF] + answer;
--- val & 0xF gets the 4 bits at the right most side of the value. e.g. 201 & 0xF --> 9 (see above info)

hexchars[val & 0xF] equals 9
--- then the 9th index in hexchars is the character "9" - that is appended to answer

val = val >> 4;
--- then we shift val 4 bits right val = val >> 4; to drop the first digit (as it is now processed) e.g. 201 >> 4 == 12

NEXT LOOP...

answer = hexchars[val & 0xF] + answer;
--- Now that val is 12, we do val & 0xF which == 12
--- 12 == 0000 1100
--- & 0xF 0000 1111
--- becomes 0000 1100 (i.e. stays at 12)

The 12th index in hexchars is "C" - that is appended to answer

The loop is finished so msg.payload gets set to answer and returned.

1 Like

Thank you so so much. You helped me so much. And thank you to everyone else that helped. Thank you all and enjoy your day and/or night further :slightly_smiling_face:

Apologies to come back but with your code @Steve-Mcl i noticed that with your size variable if the answer is anything bigger than 2 it only gives the last 2 values would there be a way to set the size to fit the answers length. i assume you wouldn't be able to do something like answer.length since the answer is being determined. If u use msg.payload.length it'll only set it to 1 since there's only 1 value inside of it

I don't follow what you're asking.

The solution is designed to handle 1 byte. If you want to send it 16 bit numbers, set size to 4.

You could have course to this dynamically by testing the value of msg.payload.

E.g...
If msg.payload > 255, set size to 4
If msg.payload > 65535, set size to 8

I see I see awesome thank you! sorry to bother

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.