How can I generate a CRC-8 checksum in PHP?
A:
Does it have to be CRC8?
On PHP.net there is an really simple implementation of CRC16 and a native version of CRC32.
If it does have to be CRC8 I would recommend coding something from the sudo code on the wikipedia page Marius pointed out.
Mark Davidson
2009-02-03 21:14:34
A:
function crcnifull ($dato, $byte)
{
static $PolyFull=0x8c;
for ($i=0; $i<8; $i++)
{
$x=$byte&1;
$byte>>=1;
if ($dato&1) $byte|=0x80;
if ($x) $byte^=$PolyFull;
$dato>>=1;
}
return $byte;
}
function crc8 (array $ar,$n=false)
{
if ($n===false) $n=count($ar);
$crcbyte=0;
for ($i=0; $i<$n; $i++) $crcbyte=crcnifull($ar[$i], $crcbyte);
return $crcbyte;
}
To use this function for a binary string you have to convert the binary string to an array first. That can be achieved like this:
function sbin2ar($sbin)
{
$ar=array();
$ll=strlen($sbin);
for ($i=0; $i<$ll; $i++) $ar[]=ord(substr($sbin,$i,1));
return $ar;
}
Example how to use the whole thing:
$crc8=crc8(sbin2ar($packet));
Bob
2010-04-03 21:57:54