---
title: "struct模块,(pack、unpack) 简单用法"
author: "westice"
date: "2011-04-07T12:01:46Z"
tags: []
categories: ["编程语言"]
slug: "struct-pack-unpack"
draft: false
lastmod: "2011-04-07T12:02:51Z"
id: 989456
url: "https://westice.iteye.com/blog/989456"
---

python中struct方便对底层数据进行操作，比如把一个数 i = 65536保存为一个4B的int型数据

```
s0 = struct.pack("<I",i)
```

 

   s0为一个字符串，长度为4，即占四个字节，这样方便传输与保存二进制数据。

   "&lt;I"，意思是按小端保存，&gt;为大端，I为无符号整型。

   还有其它类型参数：

   c:char      b:signed byte                 B:unsigned byte

   h:short    H:unsigned short            i:int; I:unsigned int

   l:long       L:unsigned long              f:float

   d:double  s:string (array of char)   p: pascal string (with count byte)

   q:long long    Q:unsigned long long

   unpack用于还原数据

   假设收到s0这个字符串

 

```
i2 = struct.unpack("<I",s0)
```

   i2为一个元组型，i2\[0]即还原的整型数字