# with open('LedBlink.bin', 'rb') as file:
#     bin_data = file.read()

# import binascii
# hex_data = binascii.hexlify(bin_data).decode('utf-8')

# with open('example.hex', 'w') as file:
#     file.write(hex_data)

def hex_to_c_array(hex_str, array_name="signature"):
    """
    将16进制字符串转换为C语言数组格式
    
    参数:
        hex_str: 输入的16进制字符串
        array_name: 生成的C数组名称，默认为"signature"
        
    返回:
        转换后的C语言数组字符串
    """
    # 移除可能存在的空格
    hex_str = hex_str.replace(" ", "")
    
    # 检查字符串长度是否为偶数
    if len(hex_str) % 2 != 0:
        raise ValueError("输入的16进制字符串长度必须为偶数")
    
    # 检查字符串是否只包含有效的16进制字符
    valid_chars = set('0123456789abcdefABCDEF')
    for c in hex_str:
        if c not in valid_chars:
            raise ValueError(f"输入的字符串包含无效的16进制字符: {c}")
    
    # 将字符串分割为2个字符一组，并转换为C语言的十六进制表示
    hex_bytes = [f"0x{hex_str[i:i+2].upper()}" for i in range(0, len(hex_str), 2)]
    
    # 组合成C语言数组格式
    array_str = f"unsigned char {array_name}[] = {{\n    {', '.join(hex_bytes)}\n}};"
    # 添加数组长度定义
    array_str += f"\nunsigned int {array_name}_len = {len(hex_bytes)};"
    
    return array_str

if __name__ == "__main__":
    # 示例16进制签名字符串
    example_hex = "3045022100f5ac9ed0bdb39e85f1bec984ca9af11822ce205508b35542d4f69d0690f639960220344724735c5e147348ac98e3d9fe9b15a9b7f0a7339b2b78fec6941eecdca301"
    
    try:
        # 转换为C数组
        c_array = hex_to_c_array(example_hex)
        
        # 打印结果
        print("转换后的C语言数组:")
        print("---------------------")
        print(c_array)
        print("---------------------")
        
        # 演示使用自定义数组名称
        custom_array = hex_to_c_array(example_hex, "my_signature")
        print("\n使用自定义名称的C语言数组:")
        print("---------------------")
        print(custom_array)
    except ValueError as e:
        print(f"转换失败: {e}")
    

