XOR on string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • snacktime

    #1

    XOR on string

    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
  • Peter Hansen

    #2
    Re: XOR on string

    snacktime wrote:[color=blue]
    > 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?[/color]

    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

    Comment

    • snacktime

      #3
      Re: XOR on string

      > lrc == Linear Redundancy Check? or Longitudinal? Note that[color=blue]
      > such terms are not precisely defined... generally just acronyms
      > people make up and stick in their user manuals for stuff. :-)
      >[/color]
      Longitudinal
      [color=blue]
      > import operator
      > lrc = reduce(operator .xor, [ord(c) for c in string])[/color]

      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

      Comment

      • Nick Craig-Wood

        #4
        Re: XOR on string

        Peter Hansen <peter@engcorp. com> wrote:[color=blue]
        > snacktime wrote:[color=green]
        > > 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?[/color]
        >
        > 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])[/color]

        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 = "abcdefghij1312 3kj12l3k1j23lk1 2j3l12kj3"' \
        'reduce(operato r.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 = "abcdefghij1312 3kj12l3k1j23lk1 2j3l12kj3"' \
        'reduce(operato r.xor, map(ord, string))'
        100000 loops, best of 3: 15.6 usec per loop

        --
        Nick Craig-Wood <nick@craig-wood.com> -- http://www.craig-wood.com/nick

        Comment

        Working...