convert char to byte representation

Peter Otten __peter__ at web.de
Mon Oct 10 14:51:44 EDT 2005


Scott David Daniels wrote:

> Philipp H. Mohr wrote:
>> I am trying to xor the byte representation of every char in a string with
>> its predecessor. But I don't know how to convert a char into its byte
>> representation.
> ord('a') == 97; chr(97) == 'a'; "ord" gives you the value of the byte.
> 
>> e.g. everything between $ and * needs to be xor:
>> $GPGSV,3,1,10,06,79,187,39,30,59,098,40,25,51,287,00,05,25,103,44*
>> to get the checksum.
> 
> Probably you want a byte-array here, rather than going char-by-char.
> Try:
>      import array
>      base = ('$GPGSV,3,1,10,06,79,187,39,30,59,098,'
>              '40,25,51,287,00,05,25,103,44*')
>      bytes = array.array('b', base[1 : -1])
>      for i in reversed(range(len(bytes))):
> bytes[i] ^= bytes[i-1]
>      result = bytes.tostring()

Seems like the OP doesn't need what he asked for. The simpler

def checksum(s):
    assert s[0] == "$"
    assert s[-1] == "*"
    result = 0
    for c in s[1:-1]:
        result ^= ord(c)
    return result

should do.

Peter




More information about the Python-list mailing list