【问题标题】:.decode('hex') Python2.7 vs Python3 [duplicate].decode('hex') Python2.7 vs Python3 [重复]
【发布时间】:2019-04-13 22:40:50
【问题描述】:

我有以下代码,它在 Python 2.7 中完全符合我的要求。它采用 regs 中的一系列整数值,并将每个值转换为其等效字符。例如,21365 ==> 0x5375 amd 将导致“Su”。

RegString = ""
    for i in range(length):
        if regs[start+i]!=0:
            print (" Regs is ", regs[start+1], " Hex  is ", hex(regs[start+i]), " Striped is ", str(format(regs[start+i],'x') ))
            RegString = RegString + str(format(regs[start+i],'x').decode('hex'))

但是在 Python 3 中,decode('hex') 会引发错误。现在,我查看了许多有关此问题的帖子,但无法将这些解决方案应用于我的问题,即修改上述代码以在 Python 3 中工作。

这是我尝试运行这段代码时的输出:

Regs 是 20341 Hex 是 0x4f75 Striped 是 4f75

Traceback(最近一次调用最后一次): Get_Regester_String 中的文件“v3Test.py”,第 23 行 RegString = RegString + str(format(regs[start+i],'x').decode('hex'))

AttributeError: 'str' 对象没有属性 'decode'

谁能指出我正确的方向来修复上述失败的语句,以便它可以在 Python 3.7 中工作“RegString = RegString + str(format(regs[start+i],'x' ).decode('hex')) “。谢谢...RDK

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    对于 python 3,使用以下过程

    bytes.fromhex(format(regs[start+i],'x')).decode('utf-8')
    

    【讨论】:

    • 非常感谢。在发布问题之前,我为此工作了几个小时。你的答案就像一个冠军,而且比我尝试的一些事情简单得多。太棒了
    猜你喜欢
    • 2016-09-08
    • 2018-09-23
    • 2021-03-04
    • 1970-01-01
    • 2020-06-21
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多