Hi, Steve-Mcl, sorry to bother you again, I found a bug in your previous function for calculating crc16 that the last two digits of the check code will not be displayed if there are 0's in it, what do I need to do to fix this bug? Thanks again!
[
{
"id": "12dd6725e2172907",
"type": "function",
"z": "434f482843cce883",
"name": "crc16_buffer",
"func": "function crc16(str) {\n const buf = Buffer.from(str, 'hex')\n let crc = 0xFFFF;\n for (let i = 0; i < buf.length; i++) {\n crc = crc ^ buf[i];\n for (let j = 0; j < 8; j++) {\n const temp = crc & 0x01;\n crc >>= 0x01;\n if (temp == 0x01) {\n crc ^= 0xA001;\n }\n }\n }\n return crc;\n}\n\nconst crc = crc16(msg.payload);\nconst arr = crc.toString(16).toUpperCase().substring(-4).split(\"\");\nmsg.payload = msg.payload + arr.splice(-2).concat(arr).join(\"\");\nreturn msg;",
"outputs": 1,
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 1630,
"y": 1540,
"wires": [
[
"2d38da89494f0166"
]
]
},
{
"id": "9bf78df919110200",
"type": "inject",
"z": "434f482843cce883",
"name": "",
"props": [
{
"p": "payload"
},
{
"p": "topic",
"vt": "str"
}
],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "fe0500010000",
"payloadType": "str",
"x": 1450,
"y": 1540,
"wires": [
[
"12dd6725e2172907"
]
]
},
{
"id": "2d38da89494f0166",
"type": "debug",
"z": "434f482843cce883",
"name": "debug 11",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "false",
"statusVal": "",
"statusType": "auto",
"x": 1800,
"y": 1540,
"wires": []
}
]
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;
The correct string should be:fe05000400009804, fe05000100008805