”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 Python 中将整数转换为字节字符串并返回?

如何在 Python 中将整数转换为字节字符串并返回?

发布于2024-11-09
浏览:472

How Can I Convert Integers to Byte Strings and Back in Python?

使用“bytes(n)”创建字节字符串

Python 3 中的“bytes(n)”函数不会将整数转换为其二进制表示形式,而是创建长度为 n 的字节字符串,并用空字节 (b'\x00') 填充。此行为源于 Python 3.2,其中引入了“to_bytes()”方法作为将整数编码为字节的方法。

To_Bytes 和 To_Bytes

“to_bytes” ()”方法允许将整数显式转换为字节表示形式,指定字节顺序(大端或小端)和长度。例如:

(1024).to_bytes(2, byteorder='big') == b'\x04\x00'

From_Bytes 和 From_Bytes

互补的“from_bytes()”方法可以将字节序列转换回整数:

int.from_bytes(b'\x04\x00', 'big') == 1024

无符号整数

“to_bytes()”方法适用于非负(无符号)整数。要处理有符号整数,需要采用稍微不同的方法:

def int_to_bytes(number: int) -> bytes:
    return number.to_bytes(length=(8   (number   (number < 0)).bit_length()) // 8, byteorder='big', signed=True)

def int_from_bytes(binary_data: bytes) -> Optional[int]:
    return int.from_bytes(binary_data, byteorder='big', signed=True)

使用这些函数,您可以对有符号整数与字节序列进行编码和解码。

版本声明 本文转载于:1729407016如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3