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

如何将十六进制字节转为整数?Python代码报错排查

十六进制字节转字符的错误修复

你的代码报错是因为chr()函数需要传入整数,但你在调用时先用hex()把整数转换成了十六进制字符串,导致类型不匹配。

错误原因拆解

  • int(sel,16):已经把0x开头的十六进制字符串转换成了对应的整数(比如0x41会转为65)
  • hex():又把这个整数转回成了十六进制格式的字符串(比如65会转为'0x41')
  • chr():接收字符串参数时就会抛出TypeError: 'str' object cannot be interpreted as an integer

修正后的代码

直接去掉多余的hex()调用,用int(sel,16)的结果作为chr()的参数即可:

for i in range(0, len(text), 2):
    sel = "0x" + text[i:i+2]
    # print(sel)
    print(chr(int(sel,16)))

简化写法

其实不需要手动拼接0x,int()函数可以直接解析不带前缀的十六进制字符串,代码可以更简洁:

for i in range(0, len(text), 2):
    char_code = int(text[i:i+2], 16)
    print(chr(char_code))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 14:59:56