CRC8-Check in PHP

前端 未结 2 1846
不思量自难忘°
不思量自难忘° 2020-12-11 11:24

How can I generate a CRC-8 checksum in PHP?

相关标签:
2条回答
  • 2020-12-11 12:05
    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));
    
    0 讨论(0)
  • 2020-12-11 12:10

    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 pseudo code on the wikipedia page Marius pointed out.

    0 讨论(0)
提交回复
热议问题