Search code examples
phpccrc16

Convert C to PHP for CRC16 Function


I need help in converting C code into PHP. The following is the C Code:

static const U16 crctab16[] = { 0x0000, 0x1189, ... };

U16 GetCrc16(const U8* pData, int nLength)
{
  U16 fcs = 0xffff;
  while(nLength > 0)
  {
    fcs = (fcs >> 8) ^ crctab16[fcs ^ *pData) & 0xff];
    nLength--; pData++;
  }
  return ~fcs;
}

I have the following PHP code that I have managed to convert thus far:

$crctab16 = array(0x0000, 0x1189, ... );

function getCrc16($pData)
{
    $hexdata = pack('H*',$pData);
    $nLength = strlen($hexdata);
    $fcs = 0xFFFF;
    $pos = 0;
    while($nLength > 0)
    {
        $fcs = ($fcs >> 8) ^ $crctab16[($fcs ^ $hexdata[$pos]) & 0xFF];
        $nLength--;
        $pos++;
    }
    return ~$fcs;
}

I have tried to run the following code:

$str = "0A1344010400010005"; 
var_dump(getCrc16($str));
var_dump(bin2hex(getCrc16($str))); // result supposed to be 08 45

It seems to be showing the wrong result. When I tried to substitute $str with other values, the result will always be the SAME.

I believe there might be something wrong with my PHP code. But, I cannot seem to figure out the cause of this.


Solution

  • I have managed to figure out the solution for this. Thanks to @nhahtdh, @Carsten, and @odiszapc who have helped.

    This is the correct PHP function:

    function getCrc16($pData)
    {
        $hexdata = pack('H*',$pData);
        $nLength = strlen($hexdata);
        $fcs = 0xFFFF;
        $pos = 0;
        while($nLength > 0)
        {
            $fcs = ($fcs >> 8) ^ $crctab16[($fcs ^ ord($hexdata[$pos])) & 0xFF];
            $nLength--;
            $pos++;
        }
        return ~$fcs;
    }
    

    It seems that I need to ord() function in the byte format data. I have figured this out following the CRC16 example provided by @Carsten.

    Thank you so much guys!