Search code examples
pythonpython-2.7structbinaryfiles

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?


Solution

  • 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.