惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
V
V2EX
博客园 - 【当耐特】
Vercel News
Vercel News
雷峰网
雷峰网
爱范儿
爱范儿
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Microsoft Azure Blog
Microsoft Azure Blog
F
Full Disclosure
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
NISL@THU
NISL@THU
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Attack and Defense Labs
Attack and Defense Labs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC
P
Proofpoint News Feed
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
K
Kaspersky official blog
I
InfoQ
Google Online Security Blog
Google Online Security Blog
L
LINUX DO - 最新话题
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
V
Visual Studio Blog
AI
AI
Schneier on Security
Schneier on Security
B
Blog RSS Feed
T
Tor Project blog
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
T
Threat Research - Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
Cyber Attacks, Cyber Crime and Cyber Security
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
V2EX - 技术
V2EX - 技术
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
A
Arctic Wolf
Webroot Blog
Webroot Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main

博客园 - 飘啊飘

一个精简的vi源码(2000行) dtruss 粗糙的翻译 gdb常用命令[转] gdb中信号的处理[转] 在linux中通过进程名获得进程id busybox0.60.3源码学习开始 pygame做的贪吃蛇 使用PYGAME开发的坦克游戏[代码][思路] 一篇很好的讲/etc/inittab的文章[转] 哲学家吃空心粉问题 《代码整洁之道》笔记之函数 使用面向对象概念优化条件判断语句的一个小应用 python生成文件树的代码 深入理解软件包的配置、编译与安装[转] pygame学习之对象移动 pywin32重启电脑 - 飘啊飘 - 博客园 解决LINUX和WINDOWS时间不一置 通过状态机实现的一个配置读取函数 UNIX基础知识--《APUE》第一章笔记
python中使用struct模块处理二进制数据
飘啊飘 · 2011-07-31 · via 博客园 - 飘啊飘

假设这样个场景:

你有个文件,里面全是二进制方式存储的整型,你需要读取出来。于是你随手写出了这样的代码:

1 = open("file","rb")
2 #读取个整型
3 data = f.read(4)
4 #读取完毕,关了文件
5 f.close()
6 #转换
7 num = int(data)

 然后就会报错:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: null byte in argument for int()

你查看下data:

data = '8\x00:\x00'

 神马!!竟然是十六进制!!这货怎么转换?

你翻开《CookBook》 里面扯了一堆不着边用不到的东西,就是没有这个问题。绝望之时,你在文档里看到了struct模块,文档里这么说:

This module performs conversions between Python values and C structs represented as Python strings. It uses format strings (explained below) as compact descriptions of the lay-out of the C structs and the intended conversion to/from Python values. This can be used in handling binary data stored in files or from network connections, among other sources.

 没错,找的就是这货!

大概看了下,主要用到的是pack 函数和unpack函数。

pack:

struct.pack(fmt, v1, v2, ...) 
Return a string containing the values v1, v2, ... packed according to the given format. The arguments must match the values required by the format exactly.

 unpack:

struct.unpack(fmt, string) 
Unpack the string (presumably packed by pack(fmt, ...)) according to the given format. The result 
is a tuple even if it contains exactly one item. The string must contain exactly the amount of data required by the format (len(string) must equal calcsize(fmt)).

下面还有个对应C语言中数据类型的表格:

Format C Type Python Notes
x pad byte no value
c char string of length 1
b signed char integer
B unsigned char integer
? _Bool bool (1)
h short integer
H unsigned short integer
i int integer
I unsigned int integer or long
l long integer
L unsigned long long
q long long long (2)
Q unsigned long long long (2)
f float float
d double float
s char[] string
p char[] string
P void * long

 怎么样?大概看明白了吧?

你把代码改成了:

= open("file","rb")
data 
= f.read(4)
#转换格式
num = struct.unpack("i",data)
f.close()
print(num)

 这样就正常输出了吧?

嘿嘿,可以早点下班了。

 如果还不明白,就接着看文档去,还有可以参考下这篇文章:

http://www.cnblogs.com/tonychopper/archive/2010/07/23/1783501.html

 再次赞颂简洁万能的Python。