【Python】bytes和hex字符串之间的相互转换。

反复在几个环境上折腾码流的拼装解析和可读化打印,总是遇到hex字符串和bytes之间的转换,记录在这里吧。

1. 在Python2.7.x上(更老的环境真心折腾不起),hex字符串和bytes之间的转换是这样的:

1 >>> a = 'aabbccddeeff'
2 >>> a_bytes = a.decode('hex')
3 >>> print(a_bytes)
4 b'\xaa\xbb\xcc\xdd\xee\xff'
5 >>> aa = a_bytes.encode('hex')
6 >>> print(aa)
7 aabbccddeeff
8 >>>

2. 在python 3环境上,因为string和bytes的实现发生了重大的变化,这个转换也不能再用encode/decode完成了。

2.1 在python3.5之前,这个转换的其中一种方式是这样的:

1 >>> a = 'aabbccddeeff'
2 >>> a_bytes = bytes.fromhex(a)
3 >>> print(a_bytes)
4 b'\xaa\xbb\xcc\xdd\xee\xff'
5 >>> aa = ''.join(['%02x' % b for b in a_bytes])
6 >>> print(aa)
7 aabbccddeeff
8 >>>

2.2 到了python 3.5之后,就可以像下面这么干了:

1 >>> a = 'aabbccddeeff'
2 >>> a_bytes = bytes.fromhex(a)
3 >>> print(a_bytes)
4 b'\xaa\xbb\xcc\xdd\xee\xff'
5 >>> aa = a_bytes.hex()
6 >>> print(aa)
7 aabbccddeeff
8 >>>

 

posted @ 2017-10-26 22:29  japhasiac  阅读(55160)  评论(1编辑  收藏  举报