LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

问题代码:

b=b'x01x02x03'
x=binascii.b2a_hex(b.decode('hex')[::-1].encode('hex'))

python2下是不报错的,因为python2内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,

即先将其他编码的字符串解码(decode)成unicode  (str-->decode()-->bytes),再从unicode编码(encode)成另一种编码(bytes-->encode()-->str)。

python3报错,因为python3内部表示为utf-8

实现读小端序显示十六进制记录
 1 import binascii
 2 
 3 f=open("d:\text","wb")
 4 f.write(bytes([0x34,0x12]))
 5 f.close()
 6 f = open("d:\text", "rb")
 7 
 8 #实现读小端序显示十六进制
 9 #way1  通过binascii包下方法
10 x=binascii.b2a_hex(f.read(2)[::-1])
11 print(x.decode())
12 
13 f.seek(0)
14 #way2  使用int.from_bytes()转为int
15 y = int.from_bytes(f.read(2),byteorder='little',signed='false')
16 print(hex(y))
17 f.close()
18 
19 
20 
21 #结果
22 1234
23 0x1234

原文地址:https://www.cnblogs.com/DirWang/p/11316674.html