Python Programming

Python 2.7和3中字节到整数的转换

Spread the love

Python 2.7 和 Python 3 对字节的处理方式差异显著。本文阐明了如何在两个版本中将字节转换为整数,并强调了关键区别。

目录

Python 2.7 和字节字符串

在 Python 2.7 中,str 类型同时处理文本和字节数据。Python 3 中的专用bytes类型在 Python 2.7 中不存在。字节字符串本质上是表示字节值的字符序列。重要的是要记住,Python 2.7 已经正式弃用,不应用于新项目。

在 Python 2.7 中将字节转换为整数

使用ord()函数可以将单个字节转换为整数:


byte_string = 'A'  # 表示'A'的字节值
integer_value = ord(byte_string)
print(integer_value)  # 输出:65

ord()提供 Unicode 代码点,对于单个字节,它与字节的数值相匹配。对于较长的字节字符串,需要进行位操作才能将其转换为更大的整数。以下示例假设小端字节序:


byte_string = 'x01x02x03' # 字节字符串示例(小端序)
integer_value = 0
for byte in byte_string:
    integer_value = (integer_value << 8) | ord(byte)
print(integer_value) # 输出:66051

这会迭代地将整数左移 8 位,并应用按位或运算以合并每个字节。对于大端序,请反转迭代。

Python 3 和bytes类型

Python 3 明确引入了bytes类型,将其与str类型(Unicode 文本)分开。bytes对象是 0 到 255 范围内整数的不可变序列。

在 Python 3 中将字节转换为整数

Python 3 提供了一种更简洁的方法。对于单个字节:


byte_data = b'x41' # 注意表示字节字面量的'b'前缀
integer_value = byte_data[0]
print(integer_value)  # 输出:65

直接访问索引 0 处的字节即可得到整数值。对于多个字节,使用int.from_bytes(),并指定字节序(endianness):


byte_data = b'x01x02x03' # 小端序示例
integer_value = int.from_bytes(byte_data, byteorder='little')
print(integer_value)  # 输出:66051

byte_data = b'x01x02x03' # 大端序示例
integer_value = int.from_bytes(byte_data, byteorder='big')
print(integer_value)  # 输出:16909060

byteorder='little' 表示最低有效字节优先,而byteorder='big' 表示最高有效字节优先。始终指定byteorder以确保可移植性;否则,将使用系统的默认值。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注