简体   繁体   中英

Reading Strings from a binary file

I have a binary file written by the delphi. This is what i know:

  • Block 1: 4 bytes, stands for a integer value of 32 bits.
  • Block 2: A String value (The length is not fixed for all binary files)
  • Block 3: 4 bytes, stands for a integer value of 32 bits.
  • Block 4: A String value (The length is not fixed for all binary files)
  • ...
  • BlockN

i made this to read the first block value:

import struct

f = open("filename", 'rb')
value = struct.unpack('i', f.read(4))

What about the Strings values? What a good solution would be like? Is there any way to iterate over the string and find the final delimiter "\\0" of each string value like in C?

It's a little more complex with the unpack if you don't know the length. I give you a reference which should solve your problem. packing and unpacking variable length array/string using the struct module in python

I discovered that Delphi use a 7 bit integer compression to specify at beginning of a string, how many bytes need to read.I found here the same algorithm implemented with python. So, i just have to pass the file into decode7bit(bytes): function and it will tell me how many bytes i have to read forward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM