I have the following string that needs to have a checksum done on it. How would I write the logic in PHP (or a function) to achive this. Here is an example that I have from documentation.
1 bytes, it is xor checksum, for example: if the packet is: 29 29 B1 00 07 0A 9F 95 38 0C 82 0D 0x82= 29 xor 29 xor B1 xor 00 xor 07 xor 0A xor 9F xor 95 xor 38 xor 0C
Where in the string above, 29 29 B1 00 07 0A 9F 95 38 0C (82) 0D is the checksum that was generated.
I got the following working and it gives the right checksum (130, 0x82) so it's promising... You could concatenate some of the below statements for a marginally better performance, I left the operations separate for readability.
<?php
// Input string. Checksum to be generated over the first 10 elements.
$string = '29 29 B1 00 07 0A 9F 95 38 0C 82 0D';
// Initial checksum
$checksum = 0;
// Split into chunks and process first 10 parts
$parts = explode(' ', $string, 11);
for ($i = 0; $i < 10; $i++) {
$part = $parts[$i];
$nr = hexdec($part);
$checksum ^= $nr;
}
// Done, bring back checksum into 0..0xff range
$checksum &= 0xff;
echo "Got checksum: ", $checksum, "\n";
?>