【问题标题】:Binary representation of complex numbers with bitstring in pythonpython中使用位串的复数的二进制表示
【发布时间】:2019-11-26 05:48:00
【问题描述】:

我有一个包含文本和二进制文件的文件。文本用于识别二进制数据块的开始和结束,它表示复数列表,例如(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)

【问题讨论】:

    标签: python python-3.x parsing complex-numbers bitstring


    【解决方案1】:

    这取决于复数在二进制数据中的编码方式。例如,它可能是浮点数,实部为 32 位,虚部为 32 位。如果是这样,那么s.readlist('2*float:32') 将读取并解释实部和虚部。

    或者它可以是每个 64 位,或者完全不同的格式。如果您有一个知道结果应该是什么的示例,那么请尝试几种格式,看看哪些有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2018-03-17
      • 2018-06-23
      相关资源
      最近更新 更多