-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbintohex.py
More file actions
98 lines (90 loc) · 1.68 KB
/
bintohex.py
File metadata and controls
98 lines (90 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def binary_to_intel_hex(binary_lines):
intel_hex = []
address = 0
for i in range(0, len(binary_lines), 16):
# Grab 16 lines at a time
chunk = binary_lines[i:i + 16]
byte_count = len(chunk)
# Convert each binary string to integer, then to hex
data = [int(line, 2) for line in chunk]
# Build the Intel HEX line
record_type = 0x00
record = [byte_count, (address >> 8) & 0xFF, address & 0xFF, record_type] + data
checksum = (-(sum(record) & 0xFF)) & 0xFF # Two's complement
# Format the record
hex_line = ":{:02X}{:04X}{:02X}".format(byte_count, address, record_type)
hex_line += "".join("{:02X}".format(b) for b in data)
hex_line += "{:02X}".format(checksum)
intel_hex.append(hex_line)
# Increment address by the byte count
address += byte_count
# Append the End of File record
intel_hex.append(":00000001FF")
return "\n".join(intel_hex)
# Example usage:
binary_lines = """00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111
00000000
00000001
00000010
00000011
00000100
00000101
00000110
00000111""".splitlines()
result = binary_to_intel_hex(binary_lines)
print(result)