Python:binascii.a2b_hex 给出“奇数字符串”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3731278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:28:14  来源:igfitidea点击:

Python: binascii.a2b_hex gives "Odd-length string"

python

提问by Magicked

I have a hex value that I'm grabbing from a text file, then I'm passing it to a2b_hex to convert it to the proper binary representation. Here is what I have:

我有一个从文本文件中获取的十六进制值,然后我将它传递给 a2b_hex 以将其转换为正确的二进制表示。这是我所拥有的:

k = open('./' + basefile + '.key', 'r')
k1 = k.read()
k.close()
my_key = binascii.a2b_hex(k1)

When I print k1, it is as expected: 81e3d6df

当我打印 k1 时,正如预期的那样:81e3d6df

Here is the error message:

这是错误消息:

Traceback (most recent call last):
  File "xor.py", line 26, in <module>
    my_key = binascii.a2b_hex(k1)
TypeError: Odd-length string

Any suggestions? Thanks!

有什么建议?谢谢!

采纳答案by Matti Virkkunen

Are you sure the file doesn't have something extra in it? Whitespace, for instance?

您确定该文件中没有其他内容吗?例如,空白?

Try k1.strip()

尝试 k1.strip()

回答by bobince

I suspect there is a trailing newline at the end of the file. Strip the string before passing it to binascii.

我怀疑文件末尾有一个尾随换行符。在将字符串传递给binascii.

Note there's now also a simpler spelling: k1.strip().decode('hex').

请注意,现在还有一个更简单的拼写:k1.strip().decode('hex').

回答by Jim Brissom

I'm more interested what happens if you execute the following code:

我对执行以下代码会发生什么更感兴趣:

with open("./" + basefile + ".key") as key_file:
   key = key_file.read()
   print len(key), key

Care to tell? There is probably some extra character you just don't see when printing. In these cases, make sure to print the length of the string.

介意告诉吗?可能有一些您在打印时看不到的额外字符。在这些情况下,请确保打印字符串的长度。

回答by Seth

read()doesn't strip newlines. If there's a '\n'at the end of your file, it'll be in k1.

read()不去除换行符。如果'\n'文件末尾有 ,它将在k1.

Try binascii.a2b_hex(k1.strip())or possibly binascii.a2b_hex(k1[:8]).

尝试binascii.a2b_hex(k1.strip())或可能binascii.a2b_hex(k1[:8])