python 二進制處理

在使用python進行二進制數據處理的時候,需要用到pack和unpack。

在pack/unpack 的參數中,除了表示格式的字母或符號,還會出現數字,通過查閱python的官方文檔,記錄如下

A format character may be preceded by an integral repeat count. For example, the format string '4h' means exactly the same as 'hhhh'. 字母前的數字表示重複該字母多少次

Whitespace characters between formats are ignored; a count and its format must not contain whitespace though.

For the 's' format character, the count is interpreted as the length of the bytes, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters. If a count is not given, it defaults to 1. For packing, the string is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting bytes object always has exactly the specified number of bytes. As a special case, '0s' means a single, empty string (while '0c' means 0 characters). 對於字符串string 和字符char,前面的數字是由差別的。string前的數字表明該string的長度。而char前的數字表示重複char多少次。

詳情請參考 python 官方文檔https://docs.python.org/3/library/struct.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章