c4onastick has asked for the wisdom of the Perl Monks concerning the following question:
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:
- Can this be done all in hex (so I don't have to keep jumping back and forth between hex, decimal and binary)?
- How can I modify this to correctly XOR the checksum and FF hex?
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!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: XOR'ing calculate a hex checksum
by halley (Prior) on Jan 28, 2008 at 17:32 UTC | |
Re: XOR'ing calculate a hex checksum
by BrowserUk (Patriarch) on Jan 28, 2008 at 17:54 UTC | |
Re: XOR'ing to calculate a hex checksum
by thospel (Hermit) on Jan 28, 2008 at 23:28 UTC | |
Re: XOR'ing calculate a hex checksum
by kyle (Abbot) on Jan 28, 2008 at 17:33 UTC | |
Re: XOR'ing calculate a hex checksum
by moritz (Cardinal) on Jan 28, 2008 at 17:26 UTC |