in reply to XOR checksum for string of bytes

Something like this would probably work fine.
my $Result = 0; foreach ( @Data ) { $Result ^= $_; }

--t. alex

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

Replies are listed 'Best First'.
Re: Re: XOR checksum for string of bytes
by derby (Abbot) on Jan 10, 2002 at 19:57 UTC
    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:~$