一:计算CRC校验函数

function calculateCRC16Modbus($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;
}

二:调用CRC校验

$request = 'XXXXXXXX';
$res = calculateCRC16Modbus($request);
echo str_pad(strtoupper(dechex($res %256)), 2, "0", STR_PAD_LEFT);//低八位
echo str_pad(strtoupper(dechex(floor($res /256))), 2, "0", STR_PAD_LEFT);高八位

huaweichenai
635 声望114 粉丝