0

I have a .bin binary file into which some data is written in the following representation.

  • id1: (int,16 bit)
  • id2: (int,16 bit)
  • time: (int,64 bit)
  • val1: (int, 16 bit)
  • val2: (double, 64 bit)

I want to read and decode the data into human-readable format. So far I am only able to read the .bin file byte by byte but have no idea how to get the corresponding data values as integers and floats. Any help would be much appreciated.

Thank you

This is how I am reading the file:

output = []

with open(filename,'rb') as fo:
    byte = fo.read(1)
    while byte:
        byte = fo.read(1)
        output.append(byte)

  • What do you read with ? –  Apr 11 '22 at 12:41
  • for integers you can use [from_bytes](https://docs.python.org/3/library/stdtypes.html#int.from_bytes) method – Nikolay Tsvetanov Apr 11 '22 at 12:48
  • 2
    You probably want the `struct` modules. You can parse longer blocks of data with single calls to `struct.unpack`; no need to read data one byte at a time. – chepner Apr 11 '22 at 12:51
  • Thank you for your comment, I will try the methods from the struct module and see if I am able to achieve what I want. – The_Learner Apr 11 '22 at 12:54
  • What should be the 'format' for struct.unpack_from()? It should be 'hhqhd' according to the data representation and the total size of the buffer should be 22 bytes. But struct.calcsize('hhqhd') gives 32? – The_Learner Apr 11 '22 at 14:05
  • I have figured it out, I also needed to specify '<' Byte order, now the problem is solved. Thank you very much for your help. – The_Learner Apr 12 '22 at 06:07

0 Answers0