1

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.

Agnius Vasiliauskas
  • 10,935
  • 5
  • 50
  • 70
Maxim Roman
  • 125
  • 1
  • 10
  • 2
    Similar question [here](https://stackoverflow.com/questions/30035582/how-to-calculate-crc16-ccitt-in-php-hex) – Jamie_D Dec 12 '18 at 07:08
  • 1
    Possible duplicate of [How to calculate CRC16 CCITT in PHP HEX?](https://stackoverflow.com/questions/30035582/how-to-calculate-crc16-ccitt-in-php-hex) – Agnius Vasiliauskas Dec 12 '18 at 07:16

1 Answers1

0

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.

Maxim Roman
  • 125
  • 1
  • 10