【问题标题】:How to convert a string to integer so i can XOR it with another integer in python如何将字符串转换为整数,以便我可以将它与 python 中的另一个整数进行异或
【发布时间】:2016-01-23 09:13:30
【问题描述】:

我有两个文件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) 函数但它改变了值,而我只想改变类型而不是转换基数中的值。有什么解决办法?

【问题讨论】:

  • 我不知道您为什么认为int(y, base=16) 会更改这些值? gist.github.com/NotTheEconomist/0e2966c9b67cb372e00c
  • 从 xor 的结果我知道它已经改变了它的值
  • @JohnSmith 这没有意义......粗略的异或改变了一个值......
  • 我的意思是 xor 的结果不是我手动执行时得到的结果,所以唯一可能出错的部分是 key 的转换

标签: python hex xor


【解决方案1】:

你对数字和它们的表示感到困惑

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

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

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)

【讨论】:

    【解决方案2】:

    你需要ord第二个字符串。正如 cmets 中所指出的,这不是您想要的输出。您需要将十六进制字符串转换为整数,然后您的 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() 
    

    【讨论】:

    • 这几乎可以保证不是他想要的......(他有一个十六进制字符串)
    • 是的,我的第二个字符串已经转换为十六进制,只是它的类型是字符串,需要是 int
    • 确实——第二个字符串只需要在异或之前进行转换。代码编辑即将到来...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2015-01-28
    • 2013-08-12
    相关资源
    最近更新 更多