我目前正在尝试从python字符串中获取字节并将其保存到signed 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中的文件中获取signed int字节的最佳方法,如果有人知道更好的方法,请帮助我。
编辑: 目前我可以采用数组中字节的字节表示法 我可以提取b' x02'但现在我无法在开头添加字符\将其转换为signed int。
答案 0 :(得分:0)
有一个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
答案 1 :(得分:0)
这是对你的评论的回答。
我想你有一个像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]
输出:
{{1}}