创建 main.js
全部内容如下:
function calculateCRC16Modbus(dataHexString) {
const dataBytes = [];
for (let i = 0; i < dataHexString.length; i += 2) {
dataBytes.push(parseInt(dataHexString.substr(i, 2), 16));
}
let crc = 0xFFFF;
const polynomial = 0xA001; // This is the polynomial x^16 + x^15 + x^2 + 1
for (const byte of dataBytes) {
crc ^= byte;
for (let i = 0; i < 8; i++) {
if (crc & 0x0001) {
crc = ((crc >> 1) ^ polynomial) & 0xFFFF;
} else {
crc >>= 1;
}
}
}
return crc.toString(16).toUpperCase();
}
const dataHexString = "7E7E011000004277123432003A020001240628104006F1F1100000427748F0F0240628104020190000002619001415221900000038121254FF030831FF021B01750845200000040003";
const crc = calculateCRC16Modbus(dataHexString);
console.log(crc);
console.log('7E7E011000004277123432003A020001240628104006F1F1100000427748F0F0240628104020190000002619001415221900000038121254FF030831FF021B017508452000000400031A79');
在cmd 使用 node main.js