用于Python3.8十六进制/编码问题的Python2.7函数
我有下面的十六进制函数,它与Python2.7配合使用效果非常好用于Python3.8十六进制/编码问题的Python2.7函数,python,python-3.x,python-2.7,sockets,hex,Python,Python 3.x,Python 2.7,Sockets,Hex,我有下面的十六进制函数,它与Python2.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, (add
#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')?
bytearray
应与2.7和3.8兼容:
def dehex(d):
return bytes(bytearray(d))
该函数的作用是什么?