#!/usr/bin/env python3 """ Binary to Text Converter for IUM files Converts .bin files to .txt format matching ium11.txt structure """ import sys import os def bin_to_txt(bin_file_path, txt_file_path=None): """ Convert binary file to text format matching the ium11.txt structure Args: bin_file_path (str): Path to input binary file txt_file_path (str): Path to output text file (optional) Returns: str: Path to generated text file """ if not os.path.exists(bin_file_path): raise FileNotFoundError(f"Binary file not found: {bin_file_path}") # Generate output filename if not provided if txt_file_path is None: base_name = os.path.splitext(bin_file_path)[0] txt_file_path = f"{base_name}_converted.txt" # Read binary file try: with open(bin_file_path, 'rb') as bin_file: binary_data = bin_file.read() except Exception as e: raise Exception(f"Error reading binary file: {e}") # Convert binary data to text format try: with open(txt_file_path, 'w') as txt_file: # Write start marker txt_file.write("start\n") # Process binary data in 4-byte chunks (32-bit words) for i in range(0, len(binary_data), 4): chunk = binary_data[i:i+4] # Pad with zeros if chunk is less than 4 bytes if len(chunk) < 4: chunk = chunk + b'\x00' * (4 - len(chunk)) # Convert to little-endian 32-bit hex value hex_value = chunk[::-1].hex().upper() # Reverse bytes for little-endian # Format as 8-character hex string hex_value = hex_value.zfill(8) # Write hex value txt_file.write(f"{hex_value}\n") # Write end marker txt_file.write("end\n") txt_file.write("\n") return txt_file_path except Exception as e: raise Exception(f"Error writing text file: {e}") def main(): """Main function to handle command line arguments""" if len(sys.argv) < 2: print("Usage: python bin_to_txt_converter.py [output_txt_file]") print("\nExample:") print(" python bin_to_txt_converter.py ium11.bin") print(" python bin_to_txt_converter.py ium11.bin ium11_converted.txt") sys.exit(1) bin_file_path = sys.argv[1] txt_file_path = sys.argv[2] if len(sys.argv) > 2 else None try: output_path = bin_to_txt(bin_file_path, txt_file_path) print(f"Successfully converted {bin_file_path} to {output_path}") # Show file sizes for verification bin_size = os.path.getsize(bin_file_path) txt_size = os.path.getsize(output_path) print(f"Binary file size: {bin_size} bytes") print(f"Text file size: {txt_size} bytes") except Exception as e: print(f"Error: {e}") sys.exit(1) if __name__ == "__main__": main()