python struct使用

作者: Lee_5566 | 来源:发表于2020-04-24 14:50 被阅读0次
image.png

struct

官方解释:Interpret strings as packed binary data.

具体作用就是用来处理字节流的,类似于c语言的struct.

API函数

struct模块中最重要的三个函数:

函数名 说明
pack(fmt, v1, v2, ...) 按照给定的格式(fmt),把数据封装成字符串(实际上是类似于c结构体的字节流)
unpack(fmt, string) 按照给定的格式(fmt)解析字节流string,返回解析出来的tuple
calcsize(fmt) 计算给定的格式(fmt)占用多少字节的内存
pack_into(fmt,buffer,offset,v1,v2…) 按照给定的格式(fmt),将数据转换成字符串(字节流),并将字节流写入以offset开始的buffer中.(buffer为可写的缓冲区,可用array模块)
pack_from(fmt,buffer,offset) 按照给定的格式(fmt)解析以offset开始的缓冲区,并返回解析结果

支持的格式

image.png

实战

格式的使用:

# -*- coding: utf-8 -*-
import struct
a=1
b=-1
print(struct.pack("h",b))
print(struct.pack("i",b))
image.png

二进制文件读写:

# -*- coding: utf-8 -*-
import struct
a=1000
b=-1000


f=open("111.bin","wb")
f.write(struct.pack("h",a))#对a装包,并写入
f.write(struct.pack("i",b))
f.close()

f=open("111.bin",'rb')
a1=f.read(2)
a2=struct.unpack("h",a1)#解包操作
b1=f.read(4)
b2=struct.unpack("i",b1)
print(a2,b2)
image.png

参考

python之struct详解
struct
python

相关文章

  • struct模块简介

    struct简介 使用struct可以在python数值和C的结构之间进行转换,表示方式为Python strin...

  • 2018-06-30 Python Struct

    Python使用struct处理二进制 例如: import struct a = 20 b = 400 s = ...

  • python struct使用

    struct 官方解释:Interpret strings as packed binary data. 具体作用...

  • Python中 struct使用

    有的时候需要用python处理二进制数据,比如,存取文件,socket操作时.这时候,可以使用python的str...

  • Python 字典基础回顾

    关键词 python、dict、data struct、python字典、python collections、...

  • 时间模块

    python 中 time 有三种格式: float struct tuple(time.struct_time ...

  • File文件读写

    一、python3读文本 二、处理二进制文件 使用struct来解析二进制数据 三、设置文件的缓冲 python文...

  • python struct

    此模块可以执行 Python 值和以 Python bytes 对象之间的转换https://www.liaoxu...

  • Day15内建模块struct&hashlib&

    struct Python提供了一个struct模块来解决bytes和其他二进制数据类型的转换。struct的pa...

  • 常用内建模块2

    struct Python提供了一个struct模块来解决bytes和其他二进制数据类型的转换。struct的pa...

网友评论

    本文标题:python struct使用

    本文链接:https://www.haomeiwen.com/subject/nhcfwhtx.html