You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Intel Hex格式8位行校验和计算器Python实现求助

Fixing Intel HEX Checksum Calculation in Python

Let's get that Intel HEX checksum working correctly! Your current code has two key issues that are throwing off the result:

  1. You're summing the ASCII byte values of the hex string (e.g., the character '1' is treated as 0x31 instead of part of the hex value 0x10).
  2. You're missing the final step required for Intel HEX checksums: calculating the 8-bit two's complement of the sum.

Intel HEX Checksum Rule Breakdown

For any line of Intel HEX data:

  • Sum all the actual byte values (including the length byte, address bytes, record type byte, and all data bytes)
  • Keep only the low 8 bits of that total sum
  • Compute the two's complement of this value (this is equivalent to 0x100 - (sum & 0xFF), then retaining just the low 8 bits)
  • The result is the valid checksum byte for the line

Corrected Code Implementation

Here's how to adjust your code to follow these rules properly:

# The hex string from your example (excluding the final checksum)
hex_line = '100000000C9425010C944D010C944D010C944D01'

# Step 1: Convert the hex string to actual binary bytes (2 characters = 1 byte)
try:
    byte_data = bytes.fromhex(hex_line)
except ValueError:
    print("Invalid hex string provided!")
    exit()

# Step 2: Calculate sum of all bytes, retain only the low 8 bits
total_sum = sum(byte_data) & 0xFF

# Step 3: Compute two's complement to get the checksum
checksum = (0x100 - total_sum) & 0xFF

# Step 4: Format as two-digit uppercase hex (matches Intel HEX convention)
checksum_hex = f"{checksum:02X}"

print(f"Calculated checksum: {checksum_hex}")  # Outputs '60' for your example

Testing Your Example

For the line you referenced (100000000C9425010C944D010C944D010C944D01), this code will output 60—which perfectly matches the expected checksum from your example.

Why Your Original Code Failed

  • the_bytes = b'100000000C9425010C944D010C944D010C944D01' treats each character as an ASCII byte. For example, b'10' becomes two separate bytes (0x31 and 0x30) instead of the single intended byte 0x10.
  • You skipped the critical two's complement step—Intel HEX checksums aren't just the sum mod 0xFF, they're the inverse of that sum mod 0xFF.

内容的提问来源于stack exchange,提问作者pawel.codes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:37:59