Python使用struct庫的用法小結(jié)
struct簡介
看到struct這么英文單詞,大家應(yīng)該并不陌生,因為c/c++中就有struct,在那里struct叫做結(jié)構(gòu)體。在Python中也使用struct,這充分說明了這個struct應(yīng)該和c/c++中的struct有很深的淵源。Python正是使用struct模塊執(zhí)行Python值和C結(jié)構(gòu)體之間的轉(zhuǎn)換,從而形成Python字節(jié)對象。它使用格式字符串作為底層C結(jié)構(gòu)體的緊湊描述,進而根據(jù)這個格式字符串轉(zhuǎn)換成Python值。
準確地講,Python沒有專門處理字節(jié)的數(shù)據(jù)類型。但由于
b'str'可以表示字節(jié),所以,字節(jié)數(shù)組=二進制str。而在C語言中,我們可以很方便地用struct、union來處理字節(jié),以及字節(jié)和int,float的轉(zhuǎn)換。故提供一個庫來做轉(zhuǎn)換。
常用函數(shù)
struct.pack(format:str, v1, v2, …)
按format的格式打包v1、v2等參數(shù)
import struct
result = [1,2,3,4,5]
print([struct.pack('<B', x) for x in result])
# [b'\x01', b'\x02', b'\x03', b'\x04', b'\x05']struct.unpack(format:str,buffer:bytes)
按format的格式解包buffer數(shù)據(jù),注意結(jié)果是一個數(shù)組
import struct
result = bytes.fromhex('10002030000000')
print(struct.unpack('<BHI', result))
# (16, 8192, 48)上代碼是按小端序列進行解析的
10被解析成了16
0020被解析成了 0x00 + 0x20 * 256 = 32*256 = 8192
30000000被解析成了 0x30 + 0x0 * 256 + 0x0 * 16³ + 0x0 * 256² = 48
struct.calcsize(format:str)
按format的格式計算這個格式本應(yīng)該的大小
import struct
print(struct.calcsize('<BHI')) # 7B是1個字節(jié),H是2個字節(jié),I是4個字節(jié),共7個字節(jié)
format參數(shù)的用法
數(shù)據(jù)
| Format | C Type | Python | 字節(jié)數(shù) |
|---|---|---|---|
| x | pad byte | None | 1 |
| c | char | int | 1 |
| b | signed char | int | 1 |
| B | unsigned char | int | 1 |
| ? | Bool | bool | 1 |
| h | short | int | 2 |
| H | unsigned short | int | 2 |
| i | int | int | 4 |
| I | unsigned int | int | 4 |
| l | long | int | 4 |
| L | unsigned long | int | 4 |
| q | long long | int | 8 |
| Q | unsigned long long | int | 8 |
| f | float | float | 4 |
| d | double | float | 8 |
| s | char[] | bytes | 1 |
| p | char[] | bytes | 1 |
| P | void * | int | 0 |
描述符
| Character | Byte order | Size | alignment |
|---|---|---|---|
@ | native | native | 湊足4個字節(jié) |
= | native | standard | 不作變化 |
< | little-endian | standard | 不作變化 |
> | big-endian | standard | 不作變化 |
! | network (= big-endian) | standard | 不作變化 |
到此這篇關(guān)于Python使用struct庫的用法小結(jié)的文章就介紹到這了,更多相關(guān)Python使用struct庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Flink與Python進行實時數(shù)據(jù)處理的基本步驟
Apache Flink是一個流處理框架,用于實時處理和分析數(shù)據(jù)流,PyFlink是Apache Flink的Python API,它允許用戶使用Python語言來編寫Flink作業(yè),進行實時數(shù)據(jù)處理,以下是如何使用Flink與Python進行實時數(shù)據(jù)處理的基本步驟,需要的朋友可以參考下2024-09-09
tensorflow中tf.reduce_mean函數(shù)的使用
這篇文章主要介紹了tensorflow中tf.reduce_mean函數(shù)的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
Python astype(np.float)函數(shù)使用方法解析
這篇文章主要介紹了Python astype(np.float)函數(shù)使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
在Python中通過threading模塊定義和調(diào)用線程的方法
由于著名的GIL的存在,Python中雖然能創(chuàng)建多條線程,但卻不能同時執(zhí)行...anyway,這里我們還是來學(xué)習(xí)一下在Python中通過threading模塊定義和調(diào)用線程的方法2016-07-07

