用于python 3.8十六进制/编码问题的python 2.7函数

时间:2020-10-06 01:16:40

标签: python python-3.x python-2.7 sockets hex

我有以下十六进制函数,可与python 2.7一起很好地工作

#Python 2.7 code
 def dehex(d):
        return "".join(map(chr, d))

test = dehex([0xff,0xff,0xff,0xff,0x71,0x7f,0xd8,0xfe,0x03,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x00])
sock.sendto(test, (addr, port))
response = sock.recv(4096)

但是在python 3.8中,它不允许我发送“字符串”,因此它希望我使用encode(),但是这与测试dehex输出混乱,并导致格式错误的字节,如下所示:

#Python 3.8 fail code
 def dehex(d):
        return "".join(map(chr, d))

test = dehex([0xff,0xff,0xff,0xff,0x71,0x7f,0xd8,0xfe,0x03,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x00])
sock.sendto(test.encode(), (addr, port))
response = sock.recv(4096)

我实际上如何在python 3.8上使用dehex函数,所以我不必使用encode('utf-8')?

1 个答案:

答案 0 :(得分:0)

bytearray应兼容2.7和3.8:

def dehex(d):
    return bytes(bytearray(d))