Search code examples
phpcrc16

CRC-16/KERMIT Implementation


I am using the following function to calculate CRC.

function crc16_kermit($string) { 

       $crc = 0; 
       for ( $x=0; $x<strlen( $string ); $x++ ) { 

          $crc = $crc ^ ord( $string[$x] ); 
          for ($y = 0; $y < 8; $y++) { 

             if ( ($crc & 0x0001) == 0x0001 ) $crc = ( ($crc >> 1 ) ^ 0x8408 ); 
             else                             $crc =    $crc >> 1; 
          } 
       } 

       $lb  = ($crc & 0xff00) >> 8; 
       $hb  = ($crc & 0x00ff) << 8; 
       $crc = $hb | $lb; 

       return $crc; 
    }

But its not showing the result as expected. ie; From this function I got CRC as '2DE3' for the hex value '6c20536574696f20322c31'. But I need to get it as 'EB3E'. I checked the value in 'https://crccalc.com/' .


Solution

  • Your code is fine. Your test is wrong. You did not convert the 6c20... to binary. 2de3 is the CRC of that ASCII string of digits and letters. If you convert it to binary, then you get eb3e.

    Though note that, for some reason, the last three lines of your routine reverses the bytes. So you will get 3eeb.