繁体   English   中英

python从二进制文件读取数据并将其写入signed int

[英]python read the data from binary file and writing it to signed int

我目前正在尝试从python字符串中获取字节并将其保存到有符号的int数组中,我尝试从文件中获取所有字节,而不是将'\\ x00'拆分成数组,然后尝试从该字节中获取int,但我一直在获取以下错误“ TypeError:无法将Unicode对象转换为字节”

file=open('norm.raw','rb')
data=file.read()
file.close()
#data=binascii.b2a_hex(data)
byteArr=str(data)[2:-1]

for byte in byteArr:
    i+=1
    if byte == "\\":
        cadena.append(byteArr[j:j+i])
        j=j+i
        i=0
for stri in cadena:
    print(int.from_bytes('\\'+stri[:-1],byteorder='big',signed='true'))

不知道这是否是从python文件中获取带符号的int字节的最佳方法,如果有人知道一种更好的方法,请帮助我。

编辑:目前,我可以采用数组中字节的字节表示法,可以提取b'x02',但现在我不能在开头添加字符\\来将其转换为带符号的int。

有一个decode字节对象起作用的decode函数。

bs = b'\x31'
x = int(bs.decode())

https://docs.python.org/3/library/stdtypes.html#bytes.decode

编辑:

以前的版本采用unicode值进行解码。 如果您的值存储在原始字节中。 然后,您可以通过以下方式获取整数。

binary_bytes = b'\xff\xf0\xff\xf0\xff\xf1\xff\xf0\xff\xf3\xff'

for i in range(len(binary_bytes)-1):
       print(int.from_bytes(binary_bytes[i:i+1], byteorder='big', signed='true'), end=', ')

输出: -1, -16, -1, -16, -1, -15, -1, -16, -1, -13, -1

这是对您的评论的答案。

我想你有一个像这样的字节范围b'\\xff\\xf0\\xff\\xf0\\xff\\xf1\\xff\\xf0\\xff\\xf3\\xff'

因此,您可以执行以下操作以获得所需的输出:

def func(a):

    data = [a[k:k+1] for k in range(len(a))]
    final = []
    for k in data:
        final.append(int.from_bytes(k, byteorder = 'big', signed = True))

    return final

a = b'\xff\xf0\xff\xf0\xff\xf1\xff\xf0\xff\xf3\xff'

print(func(a))

输出:

[-1, -16, -1, -16, -1, -15, -1, -16, -1, -13, -1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM