How to calculate CRC16 CCITT in PHP HEX?

后端 未结 3 1655
深忆病人
深忆病人 2021-01-13 03:30

I\'m trying to use a PHP CRC16 CCITT function to calculate the checksum.

A device sends me a PACKET with Checksum included:

10 00 00 00 00 00

3条回答
  •  既然无缘
    2021-01-13 04:29

    I found out from the Deplhi function how it works. It gets an byte Array, instead of Hex string for doing the job. Here is the code:

    // $commands = [0x35, 0x02, 0x02, 0x00, 0x10, 0x03];       // => 0x5ba3
    $commands = [0x44, 0x02, 0x02, 0x01, 0x10, 0x03];       // => 0x55c0
    var_dump(dechex(getChecksum($commands)));
    
    function getChecksum($byteArray) {
        $polynom = 0x8408;
        $in_crc = 0x0000;
        for ($i = 0; $i < sizeof($byteArray); $i++) {
            for ($n = 0; $n < 8; $n++) {
                if((($byteArray[$i] & 0x0001) ^ $in_crc) & 0x0001) 
                    $in_crc = ($in_crc >> 1) ^ $polynom;
                else 
                    $in_crc = $in_crc >> 1;
                $byteArray[$i] = $byteArray[$i] >> 1;
            }
            $result = $in_crc;
        }
        return $result;
    }
    

    The solution can be proved on this Online CRC Calculator. The Algorithm used is CRC-16/KERMIT.

提交回复
热议问题