python字符串转化为十六进制数据(socket发送 hex---bytes)

当时数据通过tcp转发,需要json转化为十六进制字符串

a = {"DataType":"Min","DeviceId":"test1234","Dust":"43","PM10":"142.3","PM2.5":"28. 3","AirPressure":"101","Temperature":"22","Humidity":"50","WindDirection":"2"," WindSpeed":"36.5","RecDate":"2017-05-08 00:00:02"}  # json格式

a = str(a)
b = ":".join("{:02x}".format(ord(c)) for c in a)

结果:

'7b:27:44:61:74:61:54:79:70:65:27:3a:20:27:4d:69:6e:27:2c:20:27:44:65:76:69:63:65:49:64:27:3a:20:27:74:65:73:74:31:32:33:34:27:2c:20:27:44:75:73:74:27:3a:20:27:34:33:27:2c:20:27:50:4d:31:30:27:3a:20:27:31:34:32:2e:33:27:2c:20:27:50:4d:32:2e:35:27:3a:20:27:32:38:2e:20:33:27:2c:20:27:41:69:72:50:72:65:73:73:75:72:65:27:3a:20:27:31:30:31:27:2c:20:27:54:65:6d:70:65:72:61:74:75:72:65:27:3a:20:27:32:32:27:2c:20:27:48:75:6d:69:64:69:74:79:27:3a:20:27:35:30:27:2c:20:27:57:69:6e:64:44:69:72:65:63:74:69:6f:6e:27:3a:20:27:32:27:2c:20:27:20:57:69:6e:64:53:70:65:65:64:27:3a:20:27:33:36:2e:35:27:2c:20:27:52:65:63:44:61:74:65:27:3a:20:27:32:30:31:37:2d:30:35:2d:30:38:20:30:30:3a:30:30:3a:30:32:27:7d'

没毛病

但是,如果说用socket发送,那就有问题,需要这样

a = 'aabbccddeeff'    换成上面的"7b  27  44  61  74  61  54  79  70  65  27......"
a_bytes = bytes.fromhex(a)
print(a_bytes)


b'\xaa\xbb\xcc\xdd\xee\xff'
然后
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s.settimeout(3)
s.connect((ip, port))


s.send(a_bytes)  就好了 py3.5 + 
参考:https://www.cnblogs.com/japhasiac/p/7739846.html

接收十六进制

bytes.hex(XXX)

©️2020 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值