work_script/CP02/txt_to_bin_converter.py
Ching L 40dcc0db8c docs(cp02): add documentation for new firmware utilities
- Document bin_to_txt_converter.py for binary to text conversion
  - Document txt_to_bin_converter.py for text to binary conversion
  - Document merge_encrypted_firmware.py for encrypted firmware merging
  - Add usage examples for all three new tools
2026-01-07 11:28:08 +08:00

45 lines
1.4 KiB
Python

#!/usr/bin/env python3
import sys
import struct
import re
def convert_txt_to_bin(txt_file, bin_file):
with open(txt_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
with open(bin_file, 'wb') as f:
count = 0
for line in lines:
line = line.strip()
if line == 'start' or line == 'end' or not line:
continue
# Check if line contains only hex digits (8 characters)
if re.match(r'^[0-9A-Fa-f]{8}$', line):
hex_value = line
# Convert hex string to integer
int_value = int(hex_value, 16)
count += 1
# Write first 63 complete 4-byte integers
if count <= 63:
f.write(struct.pack('<I', int_value))
# For the 64th value, only write the first byte
elif count == 64:
f.write(struct.pack('<I', int_value)[:1])
break
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python txt_to_bin_converter.py <input.txt> <output.bin>")
sys.exit(1)
txt_file = sys.argv[1]
bin_file = sys.argv[2]
try:
convert_txt_to_bin(txt_file, bin_file)
print(f"Successfully converted {txt_file} to {bin_file}")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)