Python 的 Bytearray:處理二進制數據


Bytearray 是 Python 中一種強大的內建數據類型,用於高效地管理二進制數據。與字串不同的是,Bytearray 是可變的,這意味著它的內容可以在創建後修改。因此,Bytearray 非常適合處理低層次的數據操作,比如二進制文件處理、網路數據傳輸或圖像處理等。

Bytearray 的主要特性

  1. 可變性:與字節類型(bytes)不同,Bytearray 支持對單個元素的修改。
  2. 二進制兼容性:非常適合與二進制文件格式或網路協議交互。
  3. 高效存儲:為範圍在 0–255 的整數序列提供高效的存儲方式。

 

上篇使用基本的file open+struct產生二進制資料來操作binary file,這邊來用用看bytearray

def create_binary_file_by_bytearray():
  with open("binary_data_bytearray.bin", "wb") as file:
    data = bytearray()
    for i in range(1, 11):
      data.extend(i.to_bytes(4, byteorder="little"))
    file.write(data)

差別在需要初始化,data = bytearray(),將data初始化為bytearray格式。

然後使用to_bytes函式 

to_bytes定義為:

int.to_bytes(length, byteorder, *, signed=False)

接下來即可輸出到binary_data_bytearray.bin。

 

接下來使用bytearray當成file buffer,"for i in range(0, len(data), 4):"這邊則是因為當初在產生的時候,我們使用4 byte長度,在產生的檔案上,會是類似 00 00 00 01,所以在存取資料的時候,需要使用data[i : i + 4]給number這個變數

def read_binary_file_bytearray():
  with open("binary_data_bytearray.bin", "rb") as file:
    data = bytearray(file.read())
    for i in range(0, len(data), 4):
      number = int.from_bytes(data[i : i + 4], byteorder="little")
      print(data[i : i + 4], number)

 

接下來append data,bytearray可以使用extend來append資料,但integer想要轉換成二進制一樣得使用struct模組

def append_to_binary_bytearray():
  with open("binary_data_bytearray.bin", "ab") as file:
    binary_data = bytearray() 
    for i in range(11, 16):
      binary_data.extend(bytearray(struct.pack("i", i)))
    file.write(binary_data)
文章標籤
全站熱搜
創作者介紹
創作者 Luke 的頭像
Luke

Luke的部落格

Luke 發表在 痞客邦 留言(0) 人氣(15)