def parse_protocol(hex_data): """ 解析2字节数据协议 :param hex_data: 16进制数据,可以是字符串(如"0x1A3F"或"1A3F")或整数 :return: 解析结果字典 """ if isinstance(hex_data, str): hex_str = hex_data.strip().upper() if hex_str.startswith('0X'): hex_str = hex_str[2:] value = int(hex_str, 16) elif isinstance(hex_data, int): value = hex_data else: raise ValueError("输入必须是16进制字符串或整数") if value < 0 or value > 0xFFFF: raise ValueError("输入必须是2字节数据(0x0000-0xFFFF)") result = {} result['D0_时间有效标志'] = '时间有效' if (value & 0x0001) else '时间无效' result['D1_定向数据有效标志'] = '定向数据有效' if (value & 0x0002) else '定向数据无效' result['D2_守时能力标志'] = '可守时' if (value & 0x0004) else '不可守时' loc_type = (value >> 3) & 0x03 loc_types = { 0: '记忆定位数据', 1: '卫星定位数据', 2: '惯性定位数据', 3: '组合定位数据' } result['D3-D4_定位数据类型'] = loc_types.get(loc_type, f'未知({loc_type})') time_code_type = (value >> 5) & 0x03 time_code_types = { 0: '保留', 1: '卫星时间数据', 2: '导航设备本机数据', 3: '原子钟时间' } result['D5-D6_时码数据类型'] = time_code_types.get(time_code_type, f'未知({time_code_type})') result['D7_J码有效标志'] = 'J码有效期以内' if (value & 0x0080) else 'J码有效期以外' satellite_type = (value >> 8) & 0x03 satellite_types = { 0: '保留', 1: '当前为北斗数据', 2: '保留', 3: '当前为混合数据' } result['D8-D9_卫星数据类型'] = satellite_types.get(satellite_type, f'未知({satellite_type})') result['D10_原子钟与卫星时间同步标志'] = '原子钟与卫星时间不同步' if (value & 0x0400) else '原子钟与卫星时间同步' result['D11_原子钟与卫星秒脉冲同步标志'] = '原子钟与卫星秒脉冲不同步' if (value & 0x0800) else '原子钟与卫星秒脉冲同步' result['D12_码型标志'] = 'J码' if (value & 0x1000) else '民码' result['D13_遥毙状态标志'] = '遥毙成功' if (value & 0x2000) else '遥毙无效' result['D14_J码星历准备状态1'] = 'J码星历准备好' if (value & 0x4000) else 'J码星历未准备好' result['D15_J码星历准备状态2'] = 'J码星历准备好' if (value & 0x8000) else 'J码星历未准备好' return result def main(): import sys if len(sys.argv) != 2: print("用法: python protocol_parser.py <16进制数据>") print("示例: python protocol_parser.py 0x1A3F") print("示例: python protocol_parser.py 1A3F") return hex_input = sys.argv[1] try: parsed = parse_protocol(hex_input) print("解析结果:") print("-" * 40) for key, value in parsed.items(): print(f"{key}: {value}") except ValueError as e: print(f"错误: {e}") if __name__ == "__main__": main()