網站首頁 編程語言 正文
struct簡介
看到struct這么英文單詞,大家應該并不陌生,因為c/c++中就有struct,在那里struct叫做結構體。在Python中也使用struct,這充分說明了這個struct應該和c/c++中的struct有很深的淵源。Python正是使用struct模塊執行Python值和C結構體之間的轉換,從而形成Python字節對象。它使用格式字符串作為底層C結構體的緊湊描述,進而根據這個格式字符串轉換成Python值。
準確地講,Python沒有專門處理字節的數據類型。但由于
b'str'
可以表示字節,所以,字節數組=二進制str。而在C語言中,我們可以很方便地用struct、union來處理字節,以及字節和int,float的轉換。故提供一個庫來做轉換。
常用函數
struct.pack(format:str, v1, v2, …)
按format的格式打包v1、v2等參數
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數據,注意結果是一個數組
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 * 163 + 0x0 * 2562 = 48
struct.calcsize(format:str)
按format的格式計算這個格式本應該的大小
import struct print(struct.calcsize('<BHI')) # 7
B是1個字節,H是2個字節,I是4個字節,共7個字節
format參數的用法
數據
Format | C Type | Python | 字節數 |
---|---|---|---|
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個字節 |
= |
native | standard | 不作變化 |
< |
little-endian | standard | 不作變化 |
> |
big-endian | standard | 不作變化 |
! |
network (= big-endian) | standard | 不作變化 |
原文鏈接:https://blog.csdn.net/m0_37157335/article/details/124656198
相關推薦
- 2023-05-14 windows下vscode環境c++利用matplotlibcpp繪圖_C 語言
- 2022-12-04 C++?Boost.Range與Adapters庫使用詳解_C 語言
- 2023-01-15 圖鄰接矩陣可視化解析_python
- 2022-10-18 使用shell腳本快速登錄容器的實現步驟_linux shell
- 2022-04-19 詳解C語言的mem系列函數_C 語言
- 2023-04-27 React中state屬性和生命周期的使用_React
- 2022-08-12 Go本地測試小技巧解耦任務拆解_Golang
- 2022-04-20 Selenium?三種等待方式(強制等待、隱式等待、顯示等待)_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支