How to calculate CRC16 CCITT in PHP HEX?

后端 未结 3 1659
深忆病人
深忆病人 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 was able to produce the same checksum with implementation like below:

    define('CRC16POLYN', 0x1021);
    
    function CRC16Normal($buffer) {
        $result = 0xFFFF;
        if (($length = strlen($buffer)) > 0) {
            for ($offset = 0; $offset < $length; $offset++) {
                $result ^= (ord($buffer[$offset]) << 8);
                for ($bitwise = 0; $bitwise < 8; $bitwise++) {
                    if (($result <<= 1) & 0x10000) $result ^= CRC16POLYN;
                    $result &= 0xFFFF;
                }
            }
        }
        return $result;
    }
    
    echo dechex(CRC16Normal(hex2bin('100000000000000012510908001800040214000c000c021c0002000000000000')));
    

    Above gives a077 on output.

    Code snippet found on https://forums.digitalpoint.com/threads/php-define-function-calculate-crc-16-ccitt.2584389/

提交回复
热议问题