Angin
7 October 2022 06:20
1
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?
did you mean slice ? there is no splice. There is split and there is slice.
E1cid
7 October 2022 08:36
5
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...
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;
Angin
7 October 2022 09:39
7
Thank you very much for your prompt reply!
Angin
7 October 2022 09:41
8
This method is also feasible,thank you!
system
Closed
21 October 2022 09:42
9
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.