python3中bytes、hex和字符串相互转换
1、字符串转bytes
a = 'abcd' a1 = bytes(a,encoding('utf-8'))
2、bytes转字符串
a = b'abcd' a1 = bytes.decode(a , encoding('utf-8'))
3、16进制字符串转bytes
a='01 02 03 04 05 06' a1 = a.replace(' ' ,'') a2 = bytes,fromhex(a1)
4、bytes转16进制字符串
"".join(['%02X ' % b for b in bs])
5、byte和int相互转换
b = b'\x12\x34' n = int.from_bytes(b,byteorder='big',signed=False) #b'\x12\x34'->4660 n = 4660 b = n.to_bytes(length=2,byteorder='big',signed=False) #4660->b'\x12\x34'
6、字节数组bytearray
1) 可变的字节序列,相当于bytes的可变版本
2) 创建bytearray对象的方法规则
bytearray() bytearray(整数n) bytearray(整型可迭代对象)
bytearray(b'字符串')
bytearray(字符串, encoding='utf-8')
示例:
>>> bytearray() bytearray(b'') >>> bytearray([1,2,3]) bytearray(b'\x01\x02\x03') >>> bytearray(["a","b","c"]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: an integer is required >>> bytearray(3) bytearray(b'\x00\x00\x00') >>> bytearray("abc",encoding="utf-8") bytearray(b'abc') >>> bytearray("abc") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: string argument without an encoding