Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I've got a LED display, the protocol is, as the documentation says: "one-way ASCII protocol". I'm using Device::SerialPort to communicate. The problem is that it requires a checksum for the contents of the packet I send, calculated as: LRC (checksum) calculated as XOR of all bytes in the packet upto the point before the checksum in the packet. Pardon my ignorance, but I have no idea how to do this!

Replies are listed 'Best First'.
Re: XOR checksum for string of bytes
by talexb (Chancellor) on Jan 10, 2002 at 17:56 UTC
    Something like this would probably work fine.
    my $Result = 0; foreach ( @Data ) { $Result ^= $_; }

    --t. alex

    "Excellent. Release the hounds." -- Monty Burns.

      AM,

      Just to add, the XOR operator will only work on numeric datatypes. A slight change to t. alex's code would be:

      $Result ^= ord($_);

      but then again, not knowing the packet format, you may have to pack the data and then unpack the bytes and roll through it that way.

      Update My apologies t. alex, Just as Juerd pointed out, you can XOR strings! The problem was setting $Result to 0 and then trying to XOR that with a string causes problems. So you could set $Result to "" but then $Result will have a PV value and not an IV (but as long as you know that ... )

      Moral: Mixing numerics, strings, and XOR will not produce the desired results (oh and use -w).

      -derby

        Hmm, good point, I have to admit that I was thinking (with my strong C bias) that we'd be dealing exclusively with 8-bit data. I used an XOR checksum when doing data communications through 3201 poll select. Slow as molasses at 1200, it sped up a little when we went to 9600.

        Update: Cool! My fiftieth writeup. How time flies.

        --t. alex

        "Excellent. Release the hounds." -- Monty Burns.

        Xor'ing strings is possible and fun.
        Simple example:
        perl -le'print "aaaa" ^ "+ 1)"'

        2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$