如何在Python中将字节转换为 Int?
使用Python可以轻松地将字节对象转换为整数值。 Python为我们提供了各种内置方法,如 from_bytes() 以及用于执行这种相互转换的类。
int.from_bytes() 方法
可以使用 int.from_bytes() 方法将字节值交换为 int 值。此方法至少需要Python 3.2 并具有以下语法:
Syntax: int.from_bytes(bytes, byteorder, *, signed=False)
Parameters:
- bytes – A byte object
- byteorder – Determines the order of representation of the integer value. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end. Big byte order calculates the value of an integer in base 256.
- signed – Default value – False . Indicates whether to represent 2’s complement of a number.
Returns – an int equivalent to the given byte
以下代码段指示字节到 int 对象的转换。
示例 1:
Python3
# declaring byte value
byte_val = b'\x00\x01'
# converting to int
# byteorder is big where MSB is at start
int_val = int.from_bytes(byte_val, "big")
# printing int equivalent
print(int_val)
Python3
byte_val = b'\x00\x10'
int_val = int.from_bytes(byte_val, "little")
# printing int object
print(int_val)
Python3
byte_val = b'\xfc\x00'
# 2's complement is enabled in big
# endian byte order format
int_val = int.from_bytes(byte_val, "big", signed="True")
# printing int object
print(int_val)
输出:
1
示例 2:
蟒蛇3
byte_val = b'\x00\x10'
int_val = int.from_bytes(byte_val, "little")
# printing int object
print(int_val)
输出:
4096
示例 3:
蟒蛇3
byte_val = b'\xfc\x00'
# 2's complement is enabled in big
# endian byte order format
int_val = int.from_bytes(byte_val, "big", signed="True")
# printing int object
print(int_val)
输出:
-1024