how to do bitwise exclusive or of two strings in python?

后端 未结 12 1782
攒了一身酷
攒了一身酷 2020-12-01 02:34

I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 03:22

    If you want to operate on bytes or words then you'll be better to use Python's array type instead of a string. If you are working with fixed length blocks then you may be able to use H or L format to operate on words rather than bytes, but I just used 'B' for this example:

    >>> import array
    >>> a1 = array.array('B', 'Hello, World!')
    >>> a1
    array('B', [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33])
    >>> a2 = array.array('B', ('secret'*3))
    >>> for i in range(len(a1)):
        a1[i] ^= a2[i]
    
    
    >>> a1.tostring()
    ';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
    

提交回复
热议问题