Packing data with Python

2023-11-13

Packing data with Python

06 Apr 2016

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',)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Packing data with Python 的相关文章

随机推荐

  • 【cdk的使用】C语言 跨平台生成伪随机数

    Github地址 https github com wujin1989 cdk C标准库中有rand 和srand 函数用来生成伪随机数 但是虽然在标准库里 确依然不能跨平台 因为C标准里没有明确rand 函数生成的随机数范围 比如 win
  • 【Xilinx DMA SG】Xilinx DMA SG 模式

    DMA简介 AXI 直接存储器访问 AXI DMA IP 提供高带宽直接存储器 AXI4 存储器映射和 AXI4 Stream IP 接口之间的访问 它SG模式还可以从中央处理中卸载数据移动任务 基于处理器的系统中的单元 CPU 初始化 状
  • 机器学习入门——线性回归预测广告投入数据集

    0 Advertising数据集 Advertising数据集是关于广告收益与广告在不同的媒体上投放的相关数据 分别是在TV Radio Newspaper三种媒体上投放花费与 投放所产生的收益的数据 数据共有200条 数据的格式如下 1
  • 线性回归最小二乘法和梯度下降法-详细

    原文 https blog csdn net y990041769 article details 69567838 问题描述 首先我们定义问题 线性回归要解决的问题就是根据给出的数据学习出一个线性模型 例如我们最常说的身高和体重的关系 以
  • EasyConnect linux(ubuntu 20.04)下运行报错

    EasyConnect 67186 Pango ERROR 10 01 20 576 Harfbuzz version too old 1 3 1 报错原因 本地系统更新导致相关依赖包的版本高于EasyConnect需要的版本 解决方式 下
  • vue3中采用pinia集中管理数据

    Pinia 起始于 2019 年 11 月左右的一次实验 其目的是设计一个拥有组合式 API 的 Vue 状态管理库 从那时起 我们就倾向于同时支持 Vue 2 和 Vue 3 并且不强制要求开发者使用组合式 API 下载依赖 yarn a
  • go基础+面试题(持续更新中...)

    go基础 面试题 Go基础 main 变量 变量的声明 局部变量 全局变量 常量与iota 常量 string和 byte如何取舍 string与nil类型的问题 Iota编译原理 内存四区 struct结构体 函数 make与new的区别
  • globbing

    1 globbing是什么 globbing表示通配符 BASH支持文件名通配 2 globbing常用列表及使用心得 序号 符号 使用心得 1 表示任意一个字符 注意与常规的正则表达式的区别 正则中 表示可选的 2 表示任意长度任意字符
  • STM32HAL----USB模拟串口(VCP)

    想要实现的功能是 USB模拟串口收发数据 串口助手发送数据至MCU MCU接收后返回给串口助手 当初是想用标准库做这个功能的 但是因为后来了解到STM32CubeMX这个软件 在尝试之后实在是感觉 太方便了 所以 并没有使用标准库 而是直接
  • Python---函数

    PP2study5 一 函数定义 二 函数调用 三 可变对象和不可变对象的使用 四 参数传递 4 1 以下是调用函数时可使用的正式参数类型 1 必需参数 2 关键字参数 3 默认参数 4 不定长参数 4 2 return 一 函数定义 Py
  • autoReconnect及查看和连接时间有关的系统变量与通常产生的异常

    MySQL官方不推荐使用autoReconnect true 参见http bugs mysql com bug php id 5020 注意这里说的版本是3 0 14 production 需要另外找别的办法来解决超过8小时 链接断开的问
  • 【数据结构和算法】字符串操作

    作者 Linux猿 简介 CSDN博客专家 华为云享专家 Linux C C 云计算 物联网 面试 刷题 算法尽管咨询我 关注我 有问题私聊 关注专栏 数据结构和算法成神路 精讲 优质好文持续更新中 欢迎小伙伴们点赞 收藏 留言 目录 一
  • CAsyncSocket进行UDP通信

    CAsyncSocket进行UDP通信 客户端代码 CString m ServerIP CString m ClientIP int m ClientPort CString m ReceiveData UINT m ServerPort
  • 基于用户的协同过滤算法(及3种计算用户相似度的方法)

    本文参考 推荐系统实践 中基于用户的协同过滤算法内容 基于老师上课讲解 自己实现了其中的代码 了解了整个过程 UserCF算法实现 实现原理 模拟数据 两两用户之间计算 优化后的倒查表方式计算用户相似度 采用惩罚热门物品和倒查表方式计算用户
  • vue+websocket+express+mongodb实战项目(实时聊天)(一)

    vue websocket express mongodb实战项目 实时聊天 一 在原来基础上增加了多个聊天室以及发送图片 vue websocket express mongodb实战项目 实时聊天 二 http blog csdn ne
  • ARM中的程序状态寄存器(CPSR)

    31 30 29 28 27 8 7 6 5 4 3 2 1 0 N Z C V 保留 I F T M4 M3 M2 M1 M0 N Negative Less Than I IRQ disable Z Zero F FIQ disable
  • Caffe在Linux下的安装,编译,实验

    第一部分 Caffe 简介 caffe是有伯克利视觉和学习中心 BVLC 开发 作者是伯克利博士贾杨清 caffe是一个深度学习 deep learning 框架 其具有易读 快速和模块化思想 第二部分 Caffe安装与配置 2 1 配置环
  • 彻底卸载、devtools安装问题、扩展程序的使用

    目录 一 彻底卸载 MySQL Mongo数据库 二 vue devtools 三 扩展程序的使用 一 彻底卸载 MySQL Mongo数据库 停止服务1 cmd命令 net stop mysql mongo 停止服务2 如下图 这个好 控
  • ElasticSearch笔记整理(三):Java API使用与ES中文分词

    TOC pom xml 使用maven工程构建ES Java API的测试项目 其用到的依赖如下
  • Packing data with Python

    Packing data with Python 06 Apr 2016 Defining how a sequence of bytes sits in a memory buffer or on disk can be challeng