0

I have some binary files which have header that I am interested to read. These binary Fortran files have this structure:

TYPE File_syn
    Sequence
    Character (Len=64) :: Site_ID                   !   64 bytes   64 
    Character (Len=4)  :: year                      !    4 bytes   68
    Character (Len=4)  :: mon                       !    4 bytes   72
    Real    :: lat                                  !    4 bytes   76
    Real    :: lon                                  !    4 bytes   80
    Real    :: elev                                 !    4 bytes   84
    Real    :: extras                               !    4 bytes   88
    Character (Len=32), Dimension(50) :: label      ! 1600 bytes 1688
    Character (Len=2408) :: padding                 ! 2408 bytes 4096
END TYPE File_syn

I am interested to read these files using Python and overall get the variable extra and label and this last one convert those bytes into an array character.

I tried something like this:

 with open(file_path, 'rb') as f:
    Site_ID = f.read(64)
    year = f.read(4)
    month = f.read(4)
    lat = f.read(4)
    lon = f.read(4)
    elev = f.read(4)
    extras = f.read(4)
    label = f.read(1600)
    header_file = f.read(2408)

print(extras)
print(label)

For extras I have something like this:

b'A0\x00\x00'

How could I convert to characters?

Thanks in advance

2
  • 1
    That depends on how your source defines a Real; is it an IEEE 754 floating-point value, or something else? Commented Jun 23, 2021 at 17:57
  • @chepner I only know that they were written as real (4bytes) Commented Jun 24, 2021 at 14:12

1 Answer 1

1

You can use struct module to convert binary string into float.

For example :

import struct
x = struct.unpack('f', b'A0\x00\x00')[0]

Give 1.7310239929804465e-41 as output

It's probably not the most elegant solution because you have to convert 'extras' to string.

x = struct.unpack('f', str(extras))[0]
Sign up to request clarification or add additional context in comments.

1 Comment

I found that this variable besides binary is big endian, therefore rewriting your suggestion as: x = struct.unpack('>f', str(extras))[0], I can get a tuple that I wanted. Thanks,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.