Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python XOR的问题:“;ord()应为字符,但找到长度为2的字符串;_Python_Bit Manipulation_Bitwise Operators_Binaryfiles - Fatal编程技术网

Python XOR的问题:“;ord()应为字符,但找到长度为2的字符串;

Python XOR的问题:“;ord()应为字符,但找到长度为2的字符串;,python,bit-manipulation,bitwise-operators,binaryfiles,Python,Bit Manipulation,Bitwise Operators,Binaryfiles,这段代码从两个二进制文件中读取字节,然后使用XOR进行字节比较。基本上是从密钥文件中读取一个奇数字节,然后在text.bin文件中移动该数量 密钥文件中的偶数字节是必须与text.bin文件中的字节进行比较的字节 从技术上讲,它的编写方式应该比较两个bin文件中的两个读取字节,但我得到了一个错误 output = (ord(mask)^ord(a)) # XOR TypeError: ord() expected a character, but string of length 2 f

这段代码从两个二进制文件中读取字节,然后使用XOR进行字节比较。基本上是从密钥文件中读取一个奇数字节,然后在text.bin文件中移动该数量

密钥文件中的偶数字节是必须与text.bin文件中的字节进行比较的字节

从技术上讲,它的编写方式应该比较两个bin文件中的两个读取字节,但我得到了一个错误

    output = (ord(mask)^ord(a)) # XOR
TypeError: ord() expected a character, but string of length 2 found

只有当
mask=k.read(2)
从第二个字节读取时,才会发生这种情况。
“长度为2的字符串”可能是错误的十六进制字符串,而不是字节?

导致该错误的原因是
k.read(2)
的长度为2,而
ord
要求长度为1

试试这个:

k = open ("key.bin", "rb")
t = open ("text.bin", "rb")

k.seek(0); t.seek(0); position = 0

while 1:
        offset = k.read(1)
        mask = bytes(chr(k.read(2)[1]),'utf8')
        print(str(mask))
        
        if not offset:
                break
        if not mask:
                break
        
        shift=int(ord(offset))
        print(shift)
        position = position + shift
        
        t.seek(position)
        a = t.read(1)
        
        output = (ord(mask)^ord(a))
        print (chr(output), end="")
        
k.close() ; d.close()

导致该错误的原因是
k.read(2)
的长度为2,而
ord
要求长度为1

试试这个:

k = open ("key.bin", "rb")
t = open ("text.bin", "rb")

k.seek(0); t.seek(0); position = 0

while 1:
        offset = k.read(1)
        mask = bytes(chr(k.read(2)[1]),'utf8')
        print(str(mask))
        
        if not offset:
                break
        if not mask:
                break
        
        shift=int(ord(offset))
        print(shift)
        position = position + shift
        
        t.seek(position)
        a = t.read(1)
        
        output = (ord(mask)^ord(a))
        print (chr(output), end="")
        
k.close() ; d.close()

k.read(2)
表示“从k读取2个字节”。所以
掩码
将是两个字节,除非文件位于距离末尾一个字节的位置。@rici谢谢。因此,要从特定位置读取一个字节,我需要先使用“k.seek(2)”,然后使用“k.read(1)”,这将从左侧查找第二个字节,然后读取该位置的一个字节?是的,这就是它的工作原理。
k.read(2)
表示“从k读取2个字节”。所以
掩码
将是两个字节,除非文件位于距离末尾一个字节的位置。@rici谢谢。因此,要从特定位置读取一个字节,我只需要使用“k.seek(2)”,然后使用“k.read(1)”,这将从左侧查找第二个字节,然后读取该位置的一个字节?是的,这就是它的工作方式。