简体   繁体   English

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

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

im currently trying to get the bytes from python string and save it to signed int array i try to get all the bytes from the file than split the '\\x00' in an array then try to get the int from that byte but i keep getting the following error 'TypeError: cannot convert unicode object to bytes' 我目前正在尝试从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'))

dont know if this is the best way to get the signed int bytes from a file in python, if some one knows a better way to do it please help me. 不知道这是否是从python文件中获取带符号的int字节的最佳方法,如果有人知道一种更好的方法,请帮助我。

edit: currently i can take the byte notation of a byte in the array i can extract the b'x02' but now i cant add the character \\ at the beginning to convert it to signed int. 编辑:目前,我可以采用数组中字节的字节表示法,可以提取b'x02',但现在我不能在开头添加字符\\来将其转换为带符号的int。

There is a decode function that works on a bytes object. 有一个decode字节对象起作用的decode函数。

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

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

EDIT: 编辑:

The previous version takes the unicode value to decode. 以前的版本采用unicode值进行解码。 If you have value stored in the raw byte. 如果您的值存储在原始字节中。 Then you can get integers in the following way. 然后,您可以通过以下方式获取整数。

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=', ')

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

This is an answer to your comment. 这是对您的评论的答案。

I suppose you have a range of bytes like this b'\\xff\\xf0\\xff\\xf0\\xff\\xf1\\xff\\xf0\\xff\\xf3\\xff' 我想你有一个像这样的字节范围b'\\xff\\xf0\\xff\\xf0\\xff\\xf1\\xff\\xf0\\xff\\xf3\\xff'

So, you can do somthing like this in order to have your desired output: 因此,您可以执行以下操作以获得所需的输出:

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))

Output: 输出:

[-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