str2 = b””
print(str2)
list_data = [1,2,1]
import struct
while list_data:
str1 = list_data[0]
data_bytes = struct.pack(“H”, str1)
str2 += data_bytes
list_data = list_data[1:]
print(str2)
第一次的輸出結果
= struct.pack(“>H”, str1)
“>H” #Big-endian format
1: \x00\x01
第二次的輸出結果
“H” (沒有>)
1: \x01\x00
使用<,結果同上
little-endian format
沒有附加,預設為@,
即使用本機的字元順序(大端or小端)
> 大端
< 小端
@或無 本機預設
AMD/Intel CPU使用小端
import struct
print(“>H 大端:”,struct.pack(“>H”,255))
print(“<H 小端:”,struct.pack(“<H”,255))
print(“to_bytes大端:”, (255).to_bytes(2, byteorder=”big”) )
print(“to_bytes小端:”, (255).to_bytes(2, byteorder=”little”) )
#255需要() 包覆
#第一個引數是轉換後的位元組資料長度
print( “bytes():”,bytes([255]) )
#255要用[] 包覆,不然會得到255個空位元組
![Python struct.pack() 將整數轉換為bytes ; while list: str1=list[0] ; 中間內容; list=[1:] #切片 ,遍歷list中的每一個元素,跟for i in list 類似 ; timeit() #計時 - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2022/10/20221118113743_25.png)
import timeit
#計時,number預設值為跑100萬次
![Python struct.pack() 將整數轉換為bytes ; while list: str1=list[0] ; 中間內容; list=[1:] #切片 ,遍歷list中的每一個元素,跟for i in list 類似 ; timeit() #計時 - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2022/10/20221118171709_50.png)
struct.pack()還是最快
推薦hahow線上學習python: https://igrape.net/30afN
近期留言