import numpy as np
import struct
def toDoubleList(dataStr):
bytesTotal = len(dataStr)
print("bytesTotal: ", bytesTotal)
# 下面的双斜线是除法结果为整数
segLen = bytesTotal // 8
print("segLen: ", segLen)
# 如果考虑字节序,字节序为big-endian,则以下语句改为 data = struct.unpack('>'+str(bytesTotal/8)+'d',dataStr)
# 相关匹配格式和字节序请见: https://docs.python.org/zh-cn/3/library/struct.html#struct.calcsize
data = struct.unpack(segLen * 'd', dataStr)
return data
#########
def toFloat32List(dataStr):
bytesTotal = len(dataStr)
print("bytesTotal: ", bytesTotal)
# 下面的双斜线是除法结果为整数
segLen = bytesTotal // 4
print("segLen: ", segLen)
# 如果考虑字节序,字节序为big-endian,则以下语句改为 data = struct.unpack('>'+str(bytesTotal/4)+'f',dataStr)
data = struct.unpack(segLen * 'f', dataStr)
return data
def toUint16List(dataStr):
bytesTotal = len(dataStr)
print("bytesTotal: ", bytesTotal)
# 下面的双斜线是除法结果为整数
segLen = bytesTotal // 2
print("segLen: ", segLen)
# 如果考虑字节序,字节序为big-endian,则以下语句改为 data = struct.unpack('>'+str(bytesTotal/2)+'H',dataStr)
data = struct.unpack(segLen * 'H', dataStr)
return data
def toUint32List(dataStr):
bytesTotal = len(dataStr)
print("bytesTotal: ", bytesTotal)
# 下面的双斜线是除法结果为整数
segLen = bytesTotal // 4
print("segLen: ", segLen)
# 如果考虑字节序,字节序为big-endian,则以下语句改为 data = struct.unpack('>'+str(bytesTotal/4)+'I',dataStr)
data = struct.unpack(segLen * 'I', dataStr)
return data
def toUintLongLongList(dataStr):
bytesTotal = len(dataStr)
print("bytesTotal: ", bytesTotal)
# 下面的双斜线是除法结果为整数
segLen = bytesTotal // 8
print("segLen: ", segLen)
# 如果考虑字节序,字节序为big-endian,则以下语句改为 data = struct.unpack('>'+str(bytesTotal/8)+'Q',dataStr)
data = struct.unpack(segLen * 'Q', dataStr)
return data
#### 测试代码
file_bin = "path/to/binfile"
with open(file_bin, 'rb') as f_r:
dataStr = f_r.read()
data_vs = toFloat32List(dataStr)
struct --- 将字节串解读为打包的二进制数据 — Python 3.12.0 文档