python3 字符串 hex 相互转换 代替python2 decode(‘hex’)

偏执的太偏执、 2021-09-01 00:35 577阅读 0赞

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. >>>

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

2.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. >>>

3.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. >>>

发表评论

表情:
评论列表 (有 0 条评论,577人围观)

还没有评论,来说两句吧...

相关阅读