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