Merge 2 arrays and covert it to string

Hello
i have a modbus machine respond with (2 arrays) value , msg.payload[0] is the most significant and msg.payload[1] is the Least significant

Capture2

so i want to merge this two arrays in one and covert it to string (start with 0x...)

like this Capture3

Thank you for your help !

Can you copy the input array and paste it here?

1 Like

This does what you asked for but not, I think, what you meant:

[{"id":"12ee2679.01330a","type":"inject","z":"586832c7.9dc7fc","name":"","topic":"","payload":"","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":250,"y":1740,"wires":[["6d4603bd.67f33c"]]},{"id":"6d4603bd.67f33c","type":"function","z":"586832c7.9dc7fc","name":"","func":"msg.payload = {\n    input: [17354, 784],\n}\n\nmsg.payload.output = `0x${msg.payload.input[0].toString(16)}${msg.payload.input[1].toString(16)}`\n\n\nreturn msg;","outputs":1,"noerr":0,"x":390,"y":1740,"wires":[["d73f8f6e.e183c"]]},{"id":"d73f8f6e.e183c","type":"debug","z":"586832c7.9dc7fc","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":610,"y":1740,"wires":[]}]

The reason I think it is wrong is that the output with the given input is not the expected 32bit output. Though I may be making more assumptions than warranted.

You probably need to use padStart with a leading zeros to make each string 4 characters long?

The result as written gives a value of 71,082,768 (0x43CA310), whereas you may want 1,137,312,528‬ (0x43CA0310)?

1 Like

thank you , that works !

with some editing on the node-red function ...

this is the js code : (for the function)

var highs = msg.payload[0];
var lows = msg.payload[1];
msg.payload = `0x${highs.toString(16)}${lows.toString(16)}`

return msg;

yes this is another problem, when the low word has a "0" at the beginning, the function convert it to string without "0" so the result is wrong ...

how can i solve this please ?

WOW !

i think i solved this problem

var hhigh = msg.payload.buffer[0];
var lhigh = msg.payload.buffer[1];
var hlow = msg.payload.buffer[2];
var llow = msg.payload.buffer[3];

    if (hhigh < 0x0F) {var hhighs = `0${hhigh.toString(16)}`;}
    else { hhighs = `${hhigh.toString(16)}`;}

    if (lhigh < 0x0F) {var lhighs = `0${lhigh.toString(16)}`;}
    else {lhighs = `${lhigh.toString(16)}`;}

    if (hlow < 0x0F) {var hlows = `0${hlow.toString(16)}`;}
    else {hlows = `${hlow.toString(16)}`;}

    if (llow < 0x0F) {var llows = `0${llow.toString(16)}`;}
    else {llows = `${llow.toString(16)}`;}

msg.payload = `0x${hhighs}${lhighs}${hlows}${llows}`
return msg;

enjoy !

There is a much simpler method and I gave you a clue. It is easiest to convert once you have each number as a string. Given that you only need to prefix with zero's. Assuming you are using at least node.js v8+ you have access to ES6 and therefore can use the string function mystring.padStart(4,'0').