用struct模塊
三個函數 pack()、unpack()、calcsize()
# 按照給定的格式(fmt),把數據封裝成字符串(實際上是類似於c結構體的字節流) pack(fmt, v1, v2, ...) # 按照給定的格式(fmt)解析字節流string,返回解析出來的tuple unpack(fmt, string) # 計算給定的格式(fmt)占用多少字節的內存 calcsize(fmt)
struct 類型表
| Format | C Type | Python type | Standard size | Notes |
|---|---|---|---|---|
| x | pad byte | no value | ||
| c | char | string of length 1 | 1 | |
| b | signed char | integer | 1 | (3) |
| B | unsigned char | integer | 1 | (3) |
| ? | _Bool | bool | 1 | (1) |
| h | short | integer | 2 | (3) |
| H | unsigned short | integer | 2 | (3) |
| i | int | integer | 4 | (3) |
| I | unsigned int | integer | 4 | (3) |
| l | long | integer | 4 | (3) |
| L | unsigned long | integer | 4 | (3) |
| q | long long | integer | 8 | (2), (3) |
| Q | unsigned long long | integer | 8 | (2), (3) |
| f | float | float | 4 | (4) |
| d | double | float | 8 | (4) |
| s | char[] | string | 1 | |
| p | char[] | string | ||
| P | void * | integer | (5), (3) |
