問題代碼:
b=b'\x01\x02\x03'
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