How To Iterate Through A List Using Xor In Python
So I got the following code: telegram = '$00;02;A1;00000000*49' checksum = telegram[10:18] # is 00000000 for x in telegram[1:]: x = '{0:08b}'.format(i
Solution 1:
You can skip the conversion to a binary string using the function ord()
on each character. For example:
>>>telegram = "$00;02;A1;00000000*49">>>ord(telegram[1]) ^ ord(telegram[2])
0
You can convert all the characters to ordinals with a list comprehension:
>>>[ord(n) for n in telegram[1:]] # all but first character...
[48, 48, 59, 48, 50, 59, 65, 49, 59, 48, 48, 48, 48, 48, 48, 48, 48, 42, 52, 57]
With tools in the standard library like functools.reduce and operator.xor you can XOR all the values together:
>>>import functools>>>import operator>>>functools.reduce(operator.xor,[ord(n) for n in telegram[1:]])
110
>>>format(110,'08b') # binary if needed
'01101110'
Post a Comment for "How To Iterate Through A List Using Xor In Python"