How can I split byte from string


Hello friends,
I'm a beginner, some simple flow I've already created and working on.
Now I would like to read data from the RS485 power meter concentrator. The data is loaded into a string that has 83 bytes. Data is in hex. Is here everything is OK.

I need to split the individual bytes from the string and save them to separate variables or array.
For example, four bytes from Byte (position) 11:
var NewArrayValue1 = msg.payload.string(11,4);

I read the forum, but I can not catch anything from which I would bounce off. Would you be nice and could I ask for advice? Thank you


The function node uses javascript so you should be able to find a few lines of javascript you can modify to do what you want


I was able to retrieve the data and store it as I expected. Just do not know whether it is correct to write code.

I tried to write a different way of writing code, but the result is bad. Values are written to one array cell.


It is generally better to copy/paste code rather than screenshot as it is easier for us to read and modify it. If you do that then put a line containing three backtick characters before the code and another after to stop the forum from reformatting it.
The first two lines are not required, they do nothing as you don't use the variable string and valArr1 is redifined later.
In your second example you would need something like
var valArr1 = [msg.payload[11].toString(16), msg.payload[12].toString, ...]
and again the first two lines do nothing.
However, I think your first example is easier to read so personally I would probably stick with that, or maybe remove valArr1 completely and put

msg.payload = [val1, val2, val3, val4];
return msg;

It is generally better practice to re-use the existing message and pass it on rather than creating a new one as you are.


The + operator in JS concatenates strings, which is why you end up with that result.

A better way to approach this is to use the ArrayBuffer methods -- for instance, to convert bytes 11-14 of your input buffer to a signed 32-bit integer, you can use this code:

// read 4 bytes from input buffer, starting at offset=11
var myInt = msg.payload.readInt32BE(11); // returns 815005831
// replace the payload buffer with the value, and return the msg object
msg.payload = myInt;
return msg;