簡體   English   中英

我如何從二進制文件讀取到python中的int16數組

[英]How do I read from binary file to an array of int16 in python

我正在嘗試解析一個二進制文件。 該文件包含一些數據包,每個數據包都以一個時間戳記開始,然后定義一個數組(行和列分別為int32)和數組本身。 我開始嘗試解析單個數據包,但讀取數組時遇到問題:

tsSize = 8
rowSize = 4
columnSize=4
thresholdVectorSize=4
targetsCandidatesVectorSize=4
centerOfMassVectorSize=4
bytesReadUpToNow=0
with open("C:\\outputs\\out.bin", mode='rb') as file: # b is important -> binary
    fileContent = file.read()   
    TimeS = struct.unpack("Q", fileContent[bytesReadUpToNow:bytesReadUpToNow+tsSize])[0]
    bytesReadUpToNow+=tsSize
    dt =datetime.datetime.fromtimestamp(TimeS/1000.0)
    rows, columns = struct.unpack("ii", fileContent[bytesReadUpToNow:bytesReadUpToNow+rowSize+columnSize])
    bytesReadUpToNow=bytesReadUpToNow+rowSize+columnSize
    data = struct.unpack("h" * (rows*columns), fileContent[bytesReadUpToNow:rows*columns*2+bytesReadUpToNow])[0]
    print(sys.getsizeof(data))
    print(type(data))

有沒有辦法在python中預定義數組的大小?

您可以使用“ bytearray”:

ba=bytearray(1000)      # zero-filled                                                 

In:  sys.getsizeof(ba)                                                       
Out: 1057

In:  ba[0:10]                                                                
Out: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

In:  ba[5]=255                                                              

In:  ba[0:10]                                                               
Out: bytearray(b'\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00')

編輯:

with open("data","wb") as ff: 
     ff.write(int.to_bytes(100,1,"big")) 
     ff.write(int.to_bytes(300,2,"big")) 
     ff.write(int.to_bytes(5001,4,"big")) 

ba=bytearray(7)
ba
Out: bytearray(b'\x00\x00\x00\x00\x00\x00\x00')

with open("data","rb") as ff: 
     ba[0:7]= ff.read(7) 

ba                                          
Out: bytearray(b'd\x01,\x00\x00\x13\x89')

int.from_bytes(ba[0:1],"big")
Out: 100

int.from_bytes(ba[1:3],"big")
Out: 300

int.from_bytes(ba[3:],"big") 
Out: 5001

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM