Python - 尝试从文件中提取字节时出错

Python - Error when trying to extract bytes from file

我目前正在尝试从文件中提取原始二进制字节,例如000001001000

f = open(r"file.z", "rb")
try:
    byte = f.read();
    print int(byte)
finally:
    f.close()

我之所以使用 int(byte) 是为了看看字符串的样子。 (我无法打印它,因为 [解码错误 - 输出不是 utf-8])

Traceback (most recent call last):
  File "C:\Users\werdnakof\Downloads\test.py", line 9, in <module>
    print int(byte);
ValueError: invalid literal for int() with base 10: '\x04\x80e\x06\xc0l\x06\xf0,\x02'

它returns \x04\x80e\x06\xc0l\x06\xf0,\x02

而且我不太确定从这里到哪里去。有人告诉我这是 12 位固定的,左边填充了代码。

关于如何解决这个问题的任何建议或提示?我想要的只是 12 位数,例如 000001001000

要打印二进制字符串的内容,您可以将其转换为十六进制表示:

print byte.encode('hex')

要读取二进制结构,您可以使用结构模块。

使用编码和 bin:

 bin(int(b.encode("hex"),16))

In [27]: b='\x04\x80e\x06\xc0l\x06\xf0,\x02'
In [28]: int(b.encode("hex"),16)
Out[28]: 21257928890331299851266L
In [29]: bin(int(b.encode("hex"),16))
Out[29]: '0b10010000000011001010000011011000000011011000000011011110000001011000000001



with open("file.z","rb") as f:
    for line in f:
        print(int(line.encode("hex"), 16))

你能试试这个吗

f = open("file.z", "rb")
try:
    byte = f.read();
    print(bin(int(str(byte).encode("hex"),16)))
finally:
    f.close()

来自 Padraic Cunningham 的回答