You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构造的十六进制字符串经unhexlify()处理后格式异常的原因问询

问题分析:unhexlify处理后出现原始输入字符而非预期字节的原因

先看你提供的代码:

def craft_integration(xintegration_time):
    integration_time = xintegration_time
    integration_time_str = str(integration_time)
    integration_time_str = integration_time_str.encode('utf-8')
    integration_time_hex = integration_time_str.hex()
    return integration_time_hex

def send_set_integration(xtime):
    int_time_hex = decoder_crafter.craft_integration(xtime)
    set_hex = "c1c000000000000010001100000000000000000000000004"+int_time_hex+"1400000000000000000000000000000000000000c5c4c3c2"
    set_hex = str(set_hex)
    print(set_hex)
    set_hex = unhexlify(set_hex)

现象重现

当输入为'1000'时,craft_integration()返回31303030,拼接后得到完整十六进制字符串,经unhexlify()处理后输出:

b'\xc1\xc0\x00\x00\x00\x00\x00\x00\x10\x00\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x041000\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc5\xc4\xc3\xc2'

其中\x041000是\x04与原始输入1000的组合,而非你预期的“转换后的十六进制值对应内容”。

核心原因

你的craft_integration函数逻辑和预期不符:

  • 当前逻辑是把输入值的字符串形式,每个字符转换成ASCII码的十六进制表示:
    1. 输入'1000'转成字符串后还是'1000';
    2. encode('utf-8')得到字节串b'1000'(每个字符的ASCII码:'1'=0x31,'0'=0x30);
    3. .hex()把这个字节串转换成十六进制字符串31303030;
    4. 最后unhexlify会把31303030还原回字节串b'1000',也就是你看到的原始输入字符。

简单说:你现在做的是“字符串→ASCII字节→十六进制字符串”的转换,而不是“数值→十六进制字节”的转换。

解决方案

如果你想把输入的数值转换成对应的十六进制字节(比如输入数值1000,得到对应字节\x00\x00\x03\xe8),需要修改craft_integration函数,根据你需要的字节长度和端序调整:

def craft_integration(xintegration_time):
    # 假设输入是整数,转换成4字节大端模式的十六进制字符串
    # 如果需要小端,把byteorder改成'little'
    # 字节数可以根据需求调整(比如2字节就传2)
    return xintegration_time.to_bytes(4, byteorder='big').hex()

这样输入数值1000时,to_bytes(4, 'big')会生成字节串b'\x00\x00\x03\xe8',.hex()得到000003e8,拼接后经unhexlify处理,就会得到你预期的十六进制数值对应的字节内容,而不是原始字符串的ASCII字节。

内容的提问来源于stack exchange,提问作者Lukabratzee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 17:37:46