【问题标题】:Reading binary file into different hex "types" (8bit, 16bit, 32bit, ...)将二进制文件读入不同的十六进制“类型”(8bit、16bit、32bit,...)
【发布时间】:2018-06-05 00:17:06
【问题描述】:

我有一个包含二进制数据的文件。该文件的内容只是一长行。
示例: 010101000011101010101
最初的内容是具有以下数据类型的 c++ 对象数组:

// Care pseudo code, just for visualisation
int64 var1;
int32 var2[50];
int08 var3;

我想跳过var1var3,只将var2 的值提取为一些可读的十进制值。我的想法是逐字节读取文件并将它们转换为十六进制值。在下一步中,我虽然可以“组合”(附加)其中 4 个十六进制值以获得一个 int32 值。
示例: 0x10 0xAA 0x00 0x50 -> 0x10AA0050

到目前为止我的代码:

def append_hex(a, b):
    return (a << 4) | b

with open("file.dat", "rb") as f:
    counter = 0
    tickdifcounter = 0
    current_byte=" "
    while True:
        if (counter >= 8) and (counter < 208):
            tickdifcounter+=1
            if (tickdifcounter <= 4):
                current_byte = append_hex(current_byte, f.read(1))
                if (not current_byte):
                    break
                val = ord(current_byte)
        if (tickdifcounter > 4):
            print hex(val)
            tickdifcounter = 0
            current_byte=""
        counter+=1
        if(counter == 209):    #209 bytes = int64 + (int32*50) + int08
            counter = 0
    print

现在我的问题是我的append_hex 不工作,因为变量是字符串,所以位移不工作。

我是 python 新手,所以当我能以更好的方式做某事时,请给我提示。

【问题讨论】:

    标签: python binaryfiles


    【解决方案1】:

    您可以使用 struct 模块来读取二进制文件。

    这可以帮助你Reading a binary file into a struct in Python

    【讨论】:

      【解决方案2】:

      可以使用ord(x) 方法将字符转换为int。为了得到一个多字节数的整数值,左移。例如,来自早期项目:

      def parseNumber(string, index):
          return ord(string[index])<<24 + ord(string[index+1])<<16 + \
                 ord(string[index+2])<<8+ord(string[index+3])
      

      请注意,此代码假定为大端系统,您需要反转索引以解析小端代码。

      如果您确切知道结构的大小(或者可以根据文件大小轻松计算),您可能最好使用“struct”模块。

      【讨论】:

        猜你喜欢
        • 2014-11-21
        • 2020-10-25
        • 2011-12-22
        • 1970-01-01
        • 1970-01-01
        • 2021-10-27
        • 2014-10-30
        • 2015-05-15
        • 2012-04-08
        相关资源
        最近更新 更多