Greetings Monks!
I need to calculate the hex checksum of a bunch of digits to talk to a piece of equipment at work. According to the equipment manufacturers documented serial protocol, the checksum is the "bitwise inversion (XOR) of the one byte sum with FF hex".
Here's what I have so far, it seems to work fine except for the XOR operation, so my question is two-fold:
Code:
#! C:\perl\bin\perl.exe use strict; use warnings; print checksum('000181080002020202020202'); sub checksum { my $region = shift; $region =~ s/(\w{2})(?!$)/$1,/g; my @region_array = split(/,/, $region); my $total = 0; foreach(@region_array){ $total += hex($_); } print "Total decimal: $total\n"; my $total_hex = sprintf('%X', $total); print "Total Hex: $total_hex\n"; my ($lsb) = $total_hex =~ /([a-zA-Z0-9]{2}$)/; print "LSB: $lsb\n"; my $cs_bin = $lsb ^ 0xff; my $cs_int = sprintf('%d', $cs_bin); print "CS Decimal: $cs_int\n"; my $cs_hex = sprintf('%X', $cs_int); return $cs_hex; }
Which returns:
Total decimal: 152 Total Hex: 98 LSB: 98 CS Decimal: 157 9D
From my hand calculations (and I could be mistaken here, it's been a while since I've used anything besides base-10), the check sum for this command should be 67 hex (103 decimal) but it's comming up as 157 decimal. Any insights on this problem would be greatly appreciated! Also, any comments on cleaning up this script would be great too (it's pretty messy currently). Thanks in advance!
In reply to XOR'ing to calculate a hex checksum by c4onastick
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |