# 方法一,本方法比方法二处理速度更快 import binascii data = ['FF','FF','FF','FF'] bytestring = binascii.unhexlify(''.join(data))
1 2
# 以上代码 bytestring结果如下 b'\xff\xff\xff\xff'
1 2 3 4 5
# 方法二 data = ['FF','FF','FF','FF'] bytesstring = bytes(int(x,16) for x in data) # 以上代码 bytestring结果如下 b'\xff\xff\xff\xff'
实例二
1 2 3 4 5 6 7 8 9 10 11 12
# 将ip地址转换成数据报文中bytes数据 # ip='192.168.0.120' import binascii defip2bytes(ip): b = [] ip_num_list = ip.split('.') for num in ip_num_list: b.append(hex(int(num))).replace('0x','') for i in range(len(b)): if len(b[i])<2: b[i] = '0' + b[i] return binascii.unhexlify(''.join(b))