php
function CRC16($string)
{
$crcBytes = [];
for ($i = 0; $i < strlen($string); $i += 2) {
$crcBytes[] = hexdec(substr($string, $i, 2));
}
$crc = 0xFFFF;
$polynomial = 0xA001; // This is the polynomial x^16 + x^15 + x^2 + 1
foreach ($crcBytes as $byte) {
$crc ^= $byte;
for ($i = 0; $i < 8; $i++) {
if ($crc & 0x0001) {
$crc = (($crc >> 1) ^ $polynomial) & 0xFFFF;
} else {
$crc >>= 1;
}
}
}
return $crc;
}
调用
php
$ru = $this->CRC16($str2);
我对接MODBUS 协议 最后校验位是需要 转16进制后 调换位置
php
$ru = str_pad(dechex($ru), 4, '0', STR_PAD_LEFT);
$str2 = $str2.substr($ru,-2).substr($ru,0,2);
相当于 后两位在前 , 前两位在后
感谢观看文章,