How to calculate CRC16 CCITT in PHP HEX?

后端 未结 3 1640
深忆病人
深忆病人 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:04

    So I was looking for how to calculate checksum according to [ISO/IEC 13239] using the polynomial '1021' (hex) and initial value 'FFFF' (hex). I found this link which can calculate many types of CRC. After submitting my input, I wanted the value of the field CRC-CCITT (0xFFFF), which is something like this:

    So I took the JS function (in the .js file, the function name is CRCFFFF ) that calculated the CCITT, and created the PHP version of it.

    function crcChecksum($str) {
        // The PHP version of the JS str.charCodeAt(i)
        function charCodeAt($str, $i) {
            return ord(substr($str, $i, 1));
        }
    
        $crc = 0xFFFF;
        $strlen = strlen($str);
        for($c = 0; $c < $strlen; $c++) {
            $crc ^= charCodeAt($str, $c) << 8;
            for($i = 0; $i < 8; $i++) {
                if($crc & 0x8000) {
                    $crc = ($crc << 1) ^ 0x1021;
                } else {
                    $crc = $crc << 1;
                }
            }
        }
        $hex = $crc & 0xFFFF;
        $hex = dechex($hex);
        $hex = strtoupper($hex);
    
        return $hex;
    }
    
    $result = crcChecksum('replace with your string here');// In my case, this gave me the desired output, which is '627B' (without '0x')
    

    In case you need the '0x', just add it:

    $result = '0x' . crcChecksum('replace with your string here');// result = '0x627B'
    

提交回复
热议问题