IntelHex Library

2.3.0 · active · verified Thu Apr 09

IntelHex is a Python library for manipulating Intel HEX files, which are commonly used for programming microcontrollers and memory devices. It provides functionalities to read, write, parse, modify, and analyze HEX file data. The current version is 2.3.0, with a release cadence that addresses bug fixes and introduces new API features as needed.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load an Intel HEX file, read and modify data, and then write the changes back to a new HEX file. It uses a temporary directory for file operations and highlights the use of `eolstyle` during file writing, which is crucial for cross-platform compatibility.

import tempfile
import os
from intelhex import IntelHex

# Create a dummy HEX file content
hex_content = """
:10010000214601360121470136007E012321460119FF
:100110002146017E17C20001FF50013001360120202F
:00000001FF
""".strip()

# Use a temporary file for demonstration
with tempfile.TemporaryDirectory() as tmpdir:
    hex_filepath = os.path.join(tmpdir, "example.hex")

    with open(hex_filepath, "w") as f:
        f.write(hex_content)

    print(f"Created dummy hex file at: {hex_filepath}")

    # Load the Intel HEX file
    ih = IntelHex()
    ih.loadhex(hex_filepath)

    print(f"Loaded hex file with {len(ih.segments())} segments.")

    # Read a byte at a specific address
    address_to_read = 0x100
    byte_value = ih[address_to_read]
    print(f"Byte at {hex(address_to_read)}: {hex(byte_value)}")

    # Modify a byte
    ih[0x100] = 0xAA
    print(f"Modified byte at {hex(address_to_read)} to: {hex(ih[address_to_read])}")

    # Write the modified data to a new HEX file
    output_hex_filepath = os.path.join(tmpdir, "modified.hex")
    # Using eolstyle='LF' explicitly (see warnings)
    ih.write_hex_file(output_hex_filepath, byte_count=16, eolstyle='LF')
    print(f"Modified hex file written to: {output_hex_filepath}")

    # Basic verification
    with open(output_hex_filepath, "r") as f:
        modified_content = f.read()
        if ":10010000AA4601360121470136007E012321460127" in modified_content:
            print("Verification successful: Modified byte found in output.")
        else:
            print("Verification failed.")

view raw JSON →