如何在Python中将 Int 转换为字节?
int 对象可用于以字节格式表示相同的值。整数表示一个字节,存储为数组,其最高有效位 (MSB) 存储在数组的开头或结尾。
方法一: int.tobytes()
可以使用int.to_bytes() 方法将 int 值转换为字节。该方法是在 int 值上调用的, Python 2(最低要求 Python3)不支持执行。
Syntax: int.to_bytes(length, byteorder)
Arguments :
length – desired length of the array in bytes .
byteorder – order of the array to carry out conversion of an int to bytes. 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.
Exceptions :
OverflowError is returned in case the integer value length is not large enough to be accommodated in the length of the array.
以下程序说明了该方法在Python中的用法:
Python3
# declaring an integer value
integer_val = 5
# converting int to bytes with length
# of the array as 2 and byter order as big
bytes_val = integer_val.to_bytes(2, 'big')
# printing integer in byte representation
print(bytes_val)
Python3
# declaring an integer value
integer_val = 10
# converting int to bytes with length
# of the array as 5 and byter order as
# little
bytes_val = integer_val.to_bytes(5, 'little')
# printing integer in byte representation
print(bytes_val)
Python3
# declaring an integer value
int_val = 5
# converting to string
str_val = str(int_val)
# converting string to bytes
byte_val = str_val.encode()
print(byte_val)
b'\x00\x05'
蟒蛇3
# declaring an integer value
integer_val = 10
# converting int to bytes with length
# of the array as 5 and byter order as
# little
bytes_val = integer_val.to_bytes(5, 'little')
# printing integer in byte representation
print(bytes_val)
b'\n\x00\x00\x00\x00'
方法二:整数转字符串,字符串转字节
这种方法适用于Python版本 2 和 3。此方法不将数组的长度和字节顺序作为参数。
- 以十进制格式表示的整数值可以首先使用 str()函数转换为字符串,该函数将要转换为对应字符串的整数值作为参数。
- 然后通过为每个字符选择所需的表示形式,即对字符串值进行编码,将此字符串等效项转换为字节序列。这是由 str.encode() 方法完成的。
蟒蛇3
# declaring an integer value
int_val = 5
# converting to string
str_val = str(int_val)
# converting string to bytes
byte_val = str_val.encode()
print(byte_val)
b'5'