Skip to content

Instantly share code, notes, and snippets.

@Dreyer
Created August 22, 2012 12:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dreyer/3425199 to your computer and use it in GitHub Desktop.
Save Dreyer/3425199 to your computer and use it in GitHub Desktop.
A PHP equivalent of Visual FoxPro SYS(2007) checksum CRC 16-bit.
<?php
function crc16( $str, $params = array() )
{
$defaults = array(
'initial_value' => 0xFFFF,
'polynomial' => 0x1021, // CRC-CCITT
'xor_out' => 0,
);
foreach ( $defaults as $k => $v )
{
if ( ! isset($params[$k] ) ) $params[$k] = $v;
};
$str .= '';
$crc = $params['initial_value'];
$len = strlen( $str );
$i = 0;
while ( $len-- )
{
$crc ^= ord( $str[$i++] ) << 8;
$crc &= 0xFFFF;
for ( $j = 0; $j < 8; $j+=1 )
{
$crc = ( $crc & 0x8000 ) ? ( $crc << 1 ) ^ $params['polynomial'] : $crc << 1;
$crc &= 0xFFFF;
};
};
$crc ^= $params['xor_out'];
return $crc;
};
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment