function calculateCRC16Modbus($data) {
$crc = 0xFFFF;
$polynomial = 0xA001; // This is the polynomial x^16 + x^15 + x^2 + 1
foreach ($data as $byte) {
$crc ^= $byte;
for ($i = 0; $i < 8; $i++) {
if ($crc & 0x0001) {
$crc = (($crc >> 1) ^ $polynomial) & 0xFFFF;
} else {
$crc >>= 1;
}
}
}
return $crc;
}
$dataHexString = "01031C100001";
$dataBytes = [];
for ($i = 0; $i < strlen($dataHexString); $i += 2) {
$dataBytes[] = hexdec(substr($dataHexString, $i, 2));
}
$crc = calculateCRC16Modbus($dataBytes);
echo strtoupper(dechex($crc)); // Output the CRC as an uppercase hexadecimal string
php实现计算CRC-16/MODBUS校验位
最新推荐文章于 2024-08-04 18:57:33 发布