Modbus crc16 calculation function error syntax

I used a previous crc16 calculation function, but now it prompts an error syntax. As shown in the picture.

function crc16(str){
    var buf = Buffer.from(str,'hex')
    var crc = 0xFFFF;
    for(var i = 0;i<buf.length;i++){
        crc = crc^buf[i];
        for(var j = 0;j<8;j++){
            var temp = crc & 0x01;
            crc>>=0x01;
            if(temp == 0x01){
                crc ^= 0xA001;
            }
        }
    }
    return crc;
}

var arr =crc16(msg.payload).toString(16).toUpperCase();
arr = arr.substring(-4).split("");
msg.payload = msg.payload+arr.splice(-2).concat(arr).join("");
return msg;

I temporarily used a simple replacement method, but it doesn't feel strict enough.

msg.payload = Buffer.from(msg.payload + [arr[2]+arr[3]+arr[0]+arr[1]],"hex");

Is there any way to change the error message?Thank you very much!

And what is the error message?

The error message is:

crc16-02

did you mean slice ? there is no splice. There is split and there is slice.

declare arr as an array

let arr = [];
arr = crc16(msg.payload).toString(16).toUpperCase();
arr = arr.substring(-4).split("");
msg.payload = msg.payload+arr.splice(-2).concat(arr).join("");
return msg;

The issue is monaco (trys) to help too much some times.

It is essentially pointing out the code is not great - the function returns a number, then converts to string then it is split to an array of characters. Technically, it works, but it is ugly.

Here is a very quick fix up...

image

function crc16(str) {
    const buf = Buffer.from(str, 'hex')
    let crc = 0xFFFF;
    for (let i = 0; i < buf.length; i++) {
        crc = crc ^ buf[i];
        for (let j = 0; j < 8; j++) {
            const temp = crc & 0x01;
            crc >>= 0x01;
            if (temp == 0x01) {
                crc ^= 0xA001;
            }
        }
    }
    return crc;
}

const crc = crc16(msg.payload)
const arr = crc.toString(16).toUpperCase().substring(-4).split("")
msg.payload = msg.payload + arr.splice(-2).concat(arr).join("");
return msg;

Thank you very much for your prompt reply!

This method is also feasible,thank you!

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