Packing data with Python
Defining how a sequence of bytes sits in a memory buffer or on disk can be challenging from time to time. Since everything that you’ll work with is a byte, it makes sense that we have an intuitive way to work with this information agnostic of the overlying type restrictions that the language will enforce on us.
In today’s post, I’m going to run through Python’s byte string packing and unpacking using the struct package.
Basics
From the Python documentation:
This module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.
When working with a byte string in Python, you prefix your literals with b
.
>>> b'Hello'
'Hello'
The ord
function call is used to convert a text character into its character code representation.
>>> ord(b'H')
72
>>> ord(b'e')
101
>>> ord(b'l')
108
We can use list
to convert a whole string of byte literals into an array.
>>> list(b'Hello')
[72, 101, 108, 108, 111]
The compliment to the ord
call is chr
, which converts the byte-value back into a character.
Packing
Using the struct
module, we’re offered the pack
function call. This function takes in a format of data and then the data itself. The first parameter defines how the data supplied in the second parameter should be laid out. We get started:
>>> import struct
If we pack the string 'Hello'
as single bytes:
>>> list(b'Hello')
[72, 101, 108, 108, 111]
>>> struct.pack(b'BBBBB', 72, 101, 108, 108, 111)
b'Hello'
The format string b'BBBBB'
tells pack
to pack the values supplied into a string of 5 unsigned values. If we were to use a lower case b
in our format string, pack
would expect the byte value to be signed.
>>> struct.pack(b'bbbbb', 72, 101, 108, 108, 111)
b'Hello'
This only gets interesting once we send a value that would make the request overflow:
>>> struct.pack(b'bbbbb', 72, 101, 108, 129, 111)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: byte format requires -128 <= number <= 127
The following tables have been re-produced from the Python documentation.
Byte order, size and alignment
Character | Byte order | Size | Alignment |
---|---|---|---|
@ |
native | native | native |
= |
native | standard | none |
< |
little-endian | standard | none |
> |
big-endian | standard | none |
! |
network (= big-endian) | standard | none |
Types
Format | C Type | Python type | Standard size | Notes |
---|---|---|---|---|
x |
pad byte | no value | ||
c |
char | bytes of length 1 | 1 | |
b |
signed char | integer | 1 | (1),(3) |
B |
unsigned char | integer | 1 | (3) |
? |
_Bool | bool | 1 | (1) |
h |
short | integer | 2 | (3) |
H |
unsigned short | integer | 2 | (3) |
i |
int | integer | 4 | (3) |
I |
unsigned int | integer | 4 | (3) |
l |
long | integer | 4 | (3) |
L |
unsigned long | integer | 4 | (3) |
q |
long long | integer | 8 | (2), (3) |
Q |
unsigned long long | integer | 8 | (2), (3) |
n |
ssize_t | integer | (4) | |
N |
size_t | integer | (4) | |
f |
float | float | 4 | (5) |
d |
double | float | 8 | (5) |
s |
char[] | bytes | ||
p |
char[] | bytes | ||
P |
void * | integer | (6) |
Unpacking
The direct reverse process of packing bytes into an array, is unpacking them again into usable variables inside of your python code.
>>> struct.unpack(b'BBBBB', struct.pack(b'BBBBB', 72, 101, 108, 108, 111))
(72, 101, 108, 108, 111)
>>> struct.unpack(b'5s', struct.pack(b'BBBBB', 72, 101, 108, 108, 111))
(b'Hello',)
Packing data with Python的更多相关文章
- 使用Python对Twitter进行数据挖掘(Mining Twitter Data with Python)
目录 1.Collecting data 1.1 Register Your App 1.2 Accessing the Data 1.3 Streaming 2.Text Pre-processin ...
- python data analysis | python数据预处理(基于scikit-learn模块)
原文:http://www.jianshu.com/p/94516a58314d Dataset transformations| 数据转换 Combining estimators|组合学习器 Fe ...
- Mining Twitter Data with Python
目录 1.Collecting data 1.1 Register Your App 1.2 Accessing the Data 1.3 Streaming 2.Text Pre-processin ...
- Working with Binary Data in Python
http://www.devdungeon.com/content/working-binary-data-python
- 7 Tools for Data Visualization in R, Python, and Julia
7 Tools for Data Visualization in R, Python, and Julia Last week, some examples of creating visualiz ...
- 一句Python,一句R︱pandas模块——高级版data.frame
先学了R,最近刚刚上手python,所以想着将python和R结合起来互相对比来更好理解python.最好就是一句python,对应写一句R. pandas可谓如雷贯耳,数据处理神器. 以下符号: = ...
- Python - 2. Built-in Collection Data Types
From: http://interactivepython.org/courselib/static/pythonds/Introduction/GettingStartedwithData.htm ...
- A Complete Tutorial to Learn Data Science with Python from Scratch
A Complete Tutorial to Learn Data Science with Python from Scratch Introduction It happened few year ...
- python接口测试(post,get)-传参(data和json之间的区别)
python接口测试如何正确传参: POST 传data:data是python字典格式:传参data=json.dumps(data)是字符串类型传参 #!/usr/bin/env python3 ...
随机推荐
- PTA 线性表元素的区间删除
6-8 线性表元素的区间删除 (20 分) 给定一个顺序存储的线性表,请设计一个函数删除所有值大于min而且小于max的元素.删除后表中剩余元素保持顺序存储,并且相对位置不能改变. 函数接口定义: ...
- 一次 outline 去除经验(非继承属性,看着像继承)
情况描述: 目前维护的老项目是通过 easyui 生成的 html,嵌套结构非常多,当点击元素后,会有个边框???非常影响页面美观,这是啥迷惑点击交互??? 经验告诉我,这是 css 的 outlin ...
- 自动获取IMC系统所有网络设备资产信息
1 #coding=utf8 2 3 """ 4 CMDB接口调用 5 """ 6 import csv 7 import json 8 i ...
- LamPiao靶机work_through
前言 oscp靶机系列的第二篇.只追求做出来的话,这靶机蛮简单的.但是为了提升难度,尽量避免使用msf--毕竟考试只准用一次嘛,自己写了个exp. 正文 主机发现 nmap -sP 192.168.2 ...
- 「HTML+CSS」--自定义加载动画【009】
前言 Hello!小伙伴! 首先非常感谢您阅读海轰的文章,倘若文中有错误的地方,欢迎您指出- 哈哈 自我介绍一下 昵称:海轰 标签:程序猿一只|C++选手|学生 简介:因C语言结识编程,随后转入计算机 ...
- Vscode部分快捷键 Ps的简单使用 less中的除法问题 H5 四种布局
vscode 部分快捷键 ctrl+/ 注释ctrl+回车 光标下移alt+shift+上下箭头 将本行代码向上或向下复制ul>li 自动写alt ,鼠标一直点,就会有很多光标,可以一起写ctr ...
- (十四)struts2的国际化
一.国际化的概念 国际化是指web程序在运行时,根据客户端请求的国家.语言的不同而显示不同的界面. 例如,如果请求来自中文客户端,则页面的显示,提示信息等都是中文,如果是英文客户端,则显示英文信息. ...
- 铁人三项(第五赛区)_2018_seven
铁人三项(第五赛区)_2018_seven 先来看看保护 保护全开,IDA分析 首先申请了mmap两个随机地址的空间,一个为rwx,一个为rw 读入的都shellcode长度小于等于7,且这7个字符不 ...
- 自动化kolla-ansible部署ubuntu20.04+openstack-victoria单机
自动化kolla-ansible部署ubuntu20.04+openstack-victoria单机 欢迎加QQ群:1026880196 进行交流学习 一. 环境信息 1. 硬件信息 型号:Dell ...
- Android Activity间跳转与传递数据
1 概述 Activity之间的跳转主要使用 startActivity(Intent intent); startActivityForResult(Intent intent,int reques ...