首页  >  文章  >  后端开发  >  如何在 Python 中将整数转换为字节字符串并返回?

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

Linda Hamilton
Linda Hamilton原创
2024-10-20 14:52:02770浏览

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” ()”方法允许将整数显式转换为字节表示形式,指定字节顺序(大端或小端)和长度。例如:

<code class="python">(1024).to_bytes(2, byteorder='big') == b'\x04\x00'</code>

From_Bytes 和 From_Bytes

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

<code class="python">int.from_bytes(b'\x04\x00', 'big') == 1024</code>

无符号整数

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

<code class="python">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)</code>

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

以上是如何在 Python 中将整数转换为字节字符串并返回?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn