N
N
Nahs2015-11-04 23:15:15
Python
Nahs, 2015-11-04 23:15:15

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

Should work
csum=b'\xee'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nirvimel, 2015-11-04
@Nahs

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

And a helper function for python2 where int.to_bytes() doesn't exist:
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]

T
throughtheether, 2015-11-07
@throughtheether

There is a device that receives a data packet and outputs the text transmitted in the packet.
...
The checksum is computed as the xor of all bytes 4 through 7.
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.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question