简体   繁体   中英

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'

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.

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.

There is a decode function that works on a bytes object.

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

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

EDIT:

The previous version takes the unicode value to decode. 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

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'

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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