Answer the question
In order to leave comments, you need to log in
How to xor a string?
There is a list of values of different types. According to the condition, it is necessary to "calculate as a logical operation "exclusive OR" of all bytes" the value of the checksum.
b0 = 1
b1 = 1
b2 = 4
b3 = 'ной'
csum = b0^b1^b2^b3
csum=b'\xee'
Answer the question
In order to leave comments, you need to log in
I'm afraid that a universal solution for any data types cannot be achieved, if only because the internal representation of various types depends on the interpreter and platform, and is generally not constant.
But for str and int I can offer this solution:
def xor_bytes(data):
accumulator = 0
for item in data:
if isinstance(item, int):
string = to_bytes(item)
elif isinstance(item, str):
string = item
else:
raise Exception('Invalid item type')
for char in string:
accumulator ^= (ord(char) & 0xff)
return accumulator
def to_bytes(n, length=8, endianess='big'):
h = '%x' % n
s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
return s if endianess == 'big' else s[::-1]
There is a device that receives a data packet and outputs the text transmitted in the packet.In my opinion, the easiest way is to first pack all your strings and numbers into bytes using the module struct module (struct.pack), and then xor the necessary bytes.
...
The checksum is computed as the xor of all bytes 4 through 7.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question