迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

如何将整型 int 转换为字节 bytes

作者:迹忆客 最近更新:2023/12/17 浏览次数:

将整型 int 转换为字节 bytes 是将字节 bytes 转换为整型 int 的逆操作,本文中介绍的大多数的 intbytes 的方法都是 bytesint 方法的反向方法。


Python 2.7 和 3 中 intbytes 转换的通用方法

你可以使用 Python struct 模块中的 pack 函数将整数转换为特定格式的字节。

>>> import struct
>>> struct.pack("B", 2)
'\x02'
>>> struct.pack(">H", 2)
'\x00\x02'
>>> struct.pack("<H", 2)
'\x02\x00'

struct.pack 函数中的第一个参数是格式字符串,它指定了字节格式比如长度,字节顺序(little/big endian)等。


Python 3 中新引入的 intbytes 的转换方法

使用 bytes 来进行 intbytes 的转换

在之前文章中提到过,bytes 是 Python 3 中的内置数据类型。你可以使用 bytes 轻松地将整数 0~255 转换为字节数据类型。

>>> bytes([2])
b'\x02'

通过 int.to_bytes() 方法将整型转换为字节类型

从 Python3.1 开始引入了一个引入了一个新的整数类方法 int.to_bytes()。它是上一篇文章中讨论的 int.from_bytes() 反向转换方法。

>>> (258).to_bytes(2, byteorder="little")
b'\x02\x01'
>>> (258).to_bytes(2, byteorder="big")
b'\x01\x02'
>>> (258).to_bytes(4, byteorder="little", signed=True)
b'\x02\x01\x00\x00'
>>> (-258).to_bytes(4, byteorder="little", signed=True)
b'\xfe\xfe\xff\xff'

第一个参数是转换后的字节数据长度,第二个参数 byteorder 将字节顺序定义为 little 或 big-endian,可选参数 signed 确定是否使用二进制补码来表示整数。


运行速度比较

Python 3 中, 你有 3 种方法可以转换 intbytes

  • bytes() 方法
  • struct.pack() 方法
  • int.to_bytes() 方法

我们将测试每种方法的执行时间以比较它们的性能,最后将会给出来提高程序运行速度的建议。

>>> import timeint
>>> timeit.timeit('bytes([255])', number=1000000)
0.31296982169325455
>>> timeit.timeit('struct.pack("B", 255)', setup='import struct', number=1000000)
0.2640925447800839
>>> timeit.timeit('(255).to_bytes(1, byteorder="little")', number=1000000)
0.5622947660224895
转换方法 执行时间(100 万次)
bytes() 0.31296982169325455 s
struct.pack() 0.2640925447800839 s
int.to_bytes() 0.5622947660224895 s

因此,请使用 struct.pack() 函数执行来执行整型到字节的转换以获得最佳执行性能,虽然它已在 Python 2 中引入了,生姜还是老的辣!

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便