日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Python使用struct庫(kù)的用法小結(jié)_python

作者:serfend ? 更新時(shí)間: 2022-07-02 編程語(yǔ)言

struct簡(jiǎn)介

看到struct這么英文單詞,大家應(yīng)該并不陌生,因?yàn)閏/c++中就有struct,在那里struct叫做結(jié)構(gòu)體。在Python中也使用struct,這充分說(shuō)明了這個(gè)struct應(yīng)該和c/c++中的struct有很深的淵源。Python正是使用struct模塊執(zhí)行Python值和C結(jié)構(gòu)體之間的轉(zhuǎn)換,從而形成Python字節(jié)對(duì)象。它使用格式字符串作為底層C結(jié)構(gòu)體的緊湊描述,進(jìn)而根據(jù)這個(gè)格式字符串轉(zhuǎn)換成Python值。

準(zhǔn)確地講,Python沒(méi)有專(zhuān)門(mén)處理字節(jié)的數(shù)據(jù)類(lèi)型。但由于b'str'可以表示字節(jié),所以,字節(jié)數(shù)組=二進(jìn)制str。而在C語(yǔ)言中,我們可以很方便地用struct、union來(lái)處理字節(jié),以及字節(jié)和int,float的轉(zhuǎn)換。

故提供一個(gè)庫(kù)來(lái)做轉(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é)果是一個(gè)數(shù)組

import struct
result = bytes.fromhex('10002030000000')
print(struct.unpack('<BHI', result))
# (16, 8192, 48)

上代碼是按小端序列進(jìn)行解析的

10被解析成了16

0020被解析成了 0x00 + 0x20 * 256 = 32*256 = 8192

30000000被解析成了 0x30 + 0x0 * 256 + 0x0 * 163 + 0x0 * 2562 = 48

struct.calcsize(format:str)

按format的格式計(jì)算這個(gè)格式本應(yīng)該的大小

import struct
print(struct.calcsize('<BHI')) # 7

B是1個(gè)字節(jié),H是2個(gè)字節(jié),I是4個(gè)字節(jié),共7個(gè)字節(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個(gè)字節(jié)
= native standard 不作變化
< little-endian standard 不作變化
> big-endian standard 不作變化
! network (= big-endian) standard 不作變化

原文鏈接:https://blog.csdn.net/m0_37157335/article/details/124656198

欄目分類(lèi)
最近更新