Search code examples
pythonhex-file

.hex file reading or .bin in python - getting first address value


I have various .hex files. Some of them start from address 0x0000, some from 0x3000. In the second option I have to fill the missing addresses with 'F's. But after simply converting the .bin file to .hex I don't get the knowledge about the first address. Is there a way to know it so that the program could decide whether it is neccessary to add some chars?


Solution

  • The most simple way of determining the first address in one of these .hex files would be to open it as a text file, read the second line, extract the characters in columns 4–7 and parse them as a hexadecimal number:

    with open('example.hex') as f:
        first_line = next(f)
        second_line = next(f)
        first_address_str = second_line[3:7]
        first_address = int(first_address_str, 16)
        if first_address == 0:
            # do something
        elif first_address == 0x3000:
            # do something else
        else:
            # do something else
    

    Of course, there are already libraries to make dealing with such files more convenient and reliable, for example: https://pypi.org/project/intelhex/