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

后端 未结 12 1800
攒了一身酷
攒了一身酷 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:25

    def xor_strings(s1, s2):
        max_len = max(len(s1), len(s2))
        s1 += chr(0) * (max_len - len(s1))
        s2 += chr(0) * (max_len - len(s2))
        return ''.join([chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(s1, s2)])
    

提交回复
热议问题