duanhan9479 2018-12-12 06:14
浏览 281

CRC_CCITT校验和PHP

I have a problem with getting the right checksum of the hex CommandBlock I want to send to the controller.

The existing code is in Deplhi, and I am not a good friend with Deplhi, so I want to do it in PHP. The array below is CommandBlock with the checksum (the last 2 bytes) which I have no idea how to get them:

$commandBlock = [0x10, 0x02, 0x42, 0x01, 0x02, 0x10, 0x03, **0xa3, 0xd9**];

The only thing I know is that there was used CRC_CCITT() function.

  • 写回答

1条回答 默认 最新

  • doupingtang9627 2018-12-13 09:20
    关注

    I found out from the Deplhi function how it works. It gets an byte Array, instead of Hex string for doing the job. Here is the code:

    // $commands = [0x35, 0x02, 0x02, 0x00, 0x10, 0x03];       // => 0x5ba3
    $commands = [0x44, 0x02, 0x02, 0x01, 0x10, 0x03];       // => 0x55c0
    var_dump(dechex(getChecksum($commands)));
    
    function getChecksum($byteArray) {
        $polynom = 0x8408;
        $in_crc = 0x0000;
        for ($i = 0; $i < sizeof($byteArray); $i++) {
            for ($n = 0; $n < 8; $n++) {
                if((($byteArray[$i] & 0x0001) ^ $in_crc) & 0x0001) 
                    $in_crc = ($in_crc >> 1) ^ $polynom;
                else 
                    $in_crc = $in_crc >> 1;
                $byteArray[$i] = $byteArray[$i] >> 1;
            }
            $result = $in_crc;
        }
        return $result;
    }
    

    The solution can be proved on this Online CRC Calculator. The Algorithm used is CRC-16/KERMIT.

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?