转换C到PHP的CRC16功能 [英] Convert C to PHP for CRC16 Function
问题描述
我需要转换C $ C $ç到PHP的帮助。以下是C code:
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;
}
我有以下PHP code,我已设法迄今转换:
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;
}
我试图运行下面的code:
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
这似乎是显示错误的结果。当我试图替换 $ STR
与其他值,结果将始终是相同的。
It seems to be showing the wrong result. When I tried to substitute $str
with other values, the result will always be the SAME.
我相信有可能是坏了我的PHP code。但是,我似乎无法找出这个原因。
I believe there might be something wrong with my PHP code. But, I cannot seem to figure out the cause of this.
推荐答案
我设法弄清楚这个解决方案。由于@nhahtdh,@Carsten和@odiszapc谁都有帮助。
I have managed to figure out the solution for this. Thanks to @nhahtdh, @Carsten, and @odiszapc who have helped.
这是正确的PHP函数:
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;
}
看来,我需要 ORD在字节格式的数据()
功能。我已经想通了这一点继@Carsten提供的CRC16例子。
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.
感谢你这么多的家伙!
这篇关于转换C到PHP的CRC16功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!