[英]Binary representation of complex numbers with bitstring in python
我有一個文本和二進制文件。 文本用於標識二進制數據塊的開始和結束,該二進制數據表示一個復數列表,例如(1.5 + 5.6j)(...)。
我已經實現了以下方法來檢測數據的開始和結束位置,但是我不確定如何解析數據以提取復數。
輸入文件“ short.log”:
NOW: ^@ºÿ¦ÿÉ^B<80>^AÓ^@k^C^HüÀ^Búú<88>^@^Uü4ÿ^[ÿ<88>^@»^@}^A^@N^Auÿi^Bòü5^E¿ùï^DHûÍÿö^CÈü^C^KÌ^@¡^H^D^GÿþP^E¡ö]ý<95>öñ÷Ùûøú^@j^@ END
這是讀取它的代碼:
from bitstring import ConstBitStream
import os
import struct
bin_file = 'short.log'
byte_data = b'NOW: '
def parse(byte_data):
fileSizeBytes = os.path.getsize(bin_file)
data = open(bin_file, 'rb')
s = ConstBitStream(filename=bin_file)
occurances = s.findall(byte_data, bytealigned=True)
occurances = list(occurances)
totalOccurances = len(occurances)
byteOffset = 0
occurances2 = s.findall(b' END', bytealigned=True)
occurances2 = list(occurances2)
totalOccurances2 = len(occurances2)
byteOffset = 0
for i in range(0, len(occurances)):
occuranceOffset = (hex(int(occurances[i]/8)))
s.bitpos = occurances[i]
data = s.readto(b' END')
parsedata(data)
def parsedata(data):
#Here to parse complex number
parse(byte_data)
這取決於在二進制數據中如何編碼復數。 例如,可能是浮點數,實部為32位,虛部為32位。 如果是這樣,則s.readlist('2*float:32')
將讀取並解釋實部和虛部。
也可以是每個64位,或者是完全不同的格式。 如果您有一個示例,可以知道結果是什么,那么可以嘗試幾種格式,然后看看有什么用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.