如何将字符串转换为整数,以便我可以在python中将其与另一个整数进行异或

时间:2015-10-23 18:20:30

标签: python hex xor

我有两个文件msg.logkey.log,其中第一个文件包含纯文本Hello World!,而key.log包含一个十六进制95274DE03C78B0BDEDFBEB0D的字符串,我想在这两个文件之间进行按位异或,但首先要将第一个文件msg.log转换为ASCII。
我有这段代码:

#!/usr/bin/python3

def main():
    with open ("msg.log", "r") as myfile1:
        a=myfile1.read()
    with open ("key.log", "r") as myfile2:
        b=myfile2.read()
    rr=convert_to_ascii(a)

    xored = xor_strings(a, b)
    print(xored)

def convert_to_ascii(text):
    return "".join(format(ord(char),"x") for char in text)
def xor_strings(xs, ys):
    return "".join(format(ord(x)^y) for x, y in zip(xs, ys))

if __name__ == "__main__": main() 

我收到错误,intstr无法进行异或,我尝试使用int(y,base=16)函数,但它会更改值,而我只是想更改键入而不是基数中的值转换。可能是什么解决方案?

2 个答案:

答案 0 :(得分:0)

您需要ord第二个字符串。正如评论中指出的那样,这不是您想要的输出。您需要将十六进制字符串转换为整数,然后您的xor才能正常工作。

#!/usr/bin/python3

def main():
    with open ("msg.log", "r") as myfile1:
        a=myfile1.read()
    with open ("key.log", "r") as myfile2:
        b=myfile2.read()
    rr=convert_to_ascii(a)

    xored = xor_strings(a, b)
    print(xored)

def convert_to_ascii(text):
    return "".join(format(ord(char),"x") for char in text)
def xor_strings(xs, ys):
    intlist = [int(ys[i:i+2], base=16) for i in range(0,len(ys),2)]
    return "".join(format(ord(x)^y) for x, y in zip(xs, intlist))

if __name__ == "__main__": main() 

答案 1 :(得分:0)

你对数字与他们的陈述相混淆

hex_str = "ABC123"
int_value = int(hex_str,16)
xor_value = int_value ^ xor_with_me
print hex(xor_value)

您可能希望以字节为单位对其进行xor(从问题中不清楚)

hex_str = "ABC123"
bytes_str = binascii.unhexlify(hex_str) # becomes "\xab\xc1\x23"
byte_values = [ord(x)^xor_with_me for x in bytes_str] 
xored_bytes = "".join(chr(x) for x in byte_values)
print binascii.hexlify(xored_bytes)
相关问题