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:

  1. Can this be done all in hex (so I don't have to keep jumping back and forth between hex, decimal and binary)?
  2. 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!


In reply to XOR'ing to calculate a hex checksum by c4onastick

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.