XOR on string

S

snacktime

I need to calculate the lrc of a string using an exclusive or on each
byte in the string. How would I do this in python?

Chris
 
P

Peter Hansen

snacktime said:
I need to calculate the lrc of a string using an exclusive or on each
byte in the string. How would I do this in python?

lrc == Linear Redundancy Check? or Longitudinal? Note that
such terms are not precisely defined... generally just acronyms
people make up and stick in their user manuals for stuff. :)

import operator
lrc = reduce(operator.xor, [ord(c) for c in string])

Note that this returns an integer, so if you plan
to send this as a byte or compare it to a character
received, use chr(lrc) on it first.

-Peter
 
S

snacktime

lrc == Linear Redundancy Check? or Longitudinal? Note that
such terms are not precisely defined... generally just acronyms
people make up and stick in their user manuals for stuff. :)
Longitudinal

import operator
lrc = reduce(operator.xor, [ord(c) for c in string])

That's better than what I had, which as it turned out was working I
was just calculating the lrc on one extra digit that I should have
been.

Chris
 
N

Nick Craig-Wood

Peter Hansen said:
snacktime said:
I need to calculate the lrc of a string using an exclusive or on each
byte in the string. How would I do this in python?

lrc == Linear Redundancy Check? or Longitudinal? Note that
such terms are not precisely defined... generally just acronyms
people make up and stick in their user manuals for stuff. :)

import operator
lrc = reduce(operator.xor, [ord(c) for c in string])

Or for the full functional programming effect...

lrc = reduce(operator.xor, map(ord, string))

which is slightly faster and shorter...

$ python2.4 -m timeit -s'import operator; string = "abcdefghij13123kj12l3k1j23lk12j3l12kj3"' \
'reduce(operator.xor, [ord(c) for c in string])'
10000 loops, best of 3: 20.3 usec per loop

$ python2.4 -m timeit -s'import operator; string = "abcdefghij13123kj12l3k1j23lk12j3l12kj3"' \
'reduce(operator.xor, map(ord, string))'
100000 loops, best of 3: 15.6 usec per loop
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,218
Messages
2,571,124
Members
47,727
Latest member
smavolo

Latest Threads

Top