IntelHex Library
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
- gotcha In IntelHex v2.3.0, the `IntelHex.segments()` method introduced a new optional parameter `min_gap` with a default value of `1`. This means segments with gaps smaller than 1 byte (i.e., touching segments) will now be consolidated into a single segment by default, which changes the behavior compared to previous versions that strictly separated all non-overlapping segments.
- deprecated Versions of IntelHex prior to 2.0 had significant Python 3 compatibility issues or required the `2to3` tool. While improvements were made in 2.0, ongoing fixes for Python 3 compatibility, especially for command-line scripts, continued through versions 2.1 and 2.2.
- gotcha When writing Intel HEX files using `IntelHex.write_hex_file()` (available since v2.2) or `IntelHex.tofile()` with `format='hex'` (available since v2.3.0), the default `eolstyle` is 'native' (OS-dependent). This can lead to issues if the target device or programmer expects specific line endings (e.g., CRLF for Windows-style, LF for Unix-style) regardless of the host OS.
Install
-
pip install intelhex
Imports
- IntelHex
from intelhex import IntelHex
Quickstart
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.")