Convert C to PHP for CRC16 Function

前端 未结 3 447
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 06:51

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,         


        
3条回答
  •  既然无缘
    2021-01-06 07:25

    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!

提交回复
热议问题