1 # bytes 與 int 2 b=b'\x01\x02' 3 num=int.from_bytes(b,'little') 4 print('bytes轉int:',num) 5 6 b1=num.to_bytes(2,'little') 7 print('int轉bytes:',b1) 8 9 #bytes 與十六進制string 10 hs=''.join(['%02X' %x for x in b]) 11 print('bytes轉十六進制字符串:',hs) 12 bs=bytes.fromhex(hs) 13 print('十六進制字符串轉bytes:',bs) 14 # print(bytes.fromhex(hex(78)[2:])) 15 16 #int 與 string 17 s='abcd' 18 num=int(s,16) 19 print('字符串轉int:',num) 20 print('int轉十六進制字符串:',hex(num))
輸出:
bytes轉int: 513
int轉bytes: b'\x01\x02'
bytes轉十六進制字符串: 0102
十六進制字符串轉bytes: b'\x01\x02'
字符串轉int: 43981
int轉十六進制字符串: 0xabcd
其他轉換:
int(x [,base ]) 將x轉換為一個整數
long(x [,base ]) 將x轉換為一個長整數
float(x ) 將x轉換到一個浮點數
str(x ) 將對象 x 轉換為字符串
eval(str ) 用來計算在字符串中的有效
Python表達式,並返回一個對象
tuple(s ) 將序列 s 轉換為一個元組
list(s ) 將序列 s 轉換為一個列表
chr(x ) 將一個整數轉換為一個字符
ord(x ) 將一個字符轉換為它的整數值
hex(x ) 將一個整數轉換為一個十六進制字符串
oct(x ) 將一個整數轉換為一個八進制字符串
以下是 bytes 的語法:
class bytes([source[, encoding[, errors]]])
參數
- 如果 source 為整數,則返回一個長度為 source 的初始化數組;
- 如果 source 為字符串,則按照指定的 encoding 將字符串轉換為字節序列;
- 如果 source 為可迭代類型,則元素必須為[0 ,255] 中的整數;
- 如果 source 為與 buffer 接口一致的對象,則此對象也可以被用於初始化 bytearray。
- 如果沒有輸入任何參數,默認就是初始化數組為0個元素。