打印表示整数的字节数组的Python程序
给定一个整数N ,任务是编写一个Python程序来将这个数字的字节表示为一个数组。
一个字节是一组 8 位。任何整数都可以以字节和位的形式表示。我们一般用十六进制码来表示一个字节。单个十六进制字符可以表示 4 位,因此使用一对十六进制字符来表示一个字节。
例子:
Input: N = 543
Output: [‘0x2’, ‘0x1f’]
Explanation: 543 can be represented as 1000011111 in binary which can be grouped as (10)(00011111), each group representing a byte. In hexadecimal form, this number will be (0x02)(0x1F).
Input: N = 17292567
Output: [‘0x1’, ‘0x7’, ‘0xdd’, ‘0x17’]
Explanation: 17292567 can be represented as 1000001111101110100010111 in binary which can be grouped as (1)(00000111)(11011101)(00010111), each group representing a byte. In hexadecimal form, this number will be (0x1), (0x7), (0xdd), (0x17).
方法一(手动转换):
就像我们将十进制数转换为二进制数一样,我们可以将其转换为以 256 为基数的数字,这将为我们提供表示给定数字字节的 8 位数字。
下面是实现上述方法的代码:
Python3
n = 17292567
# Initialize the empty array
array = []
# Get the hexadecimal form
while(n):
r = n % 256
n = n//256
array.append(hex(r))
# Reverse the array to get the MSB to left
array.reverse()
print(array)
Python3
import math
n = 543
# Calculate the length of array
size = int(math.log(n, 256))+1
# Use the method to_bytes() with "big"
# or "little" property We need to apply
# hex() method to avoid the conversion
# into ASCII letters
hexForm = n.to_bytes(size, "big").hex()
# Append 8 bits together ie pair of 4 bits to get a byte
array = []
for i in range(0, len(hexForm), 2):
array.append('0x'+hexForm[i]+hexForm[i+1])
print(array)
Python3
n = 8745
# Get string representation of hex code
hexcode = "%x" % n
# Pad an extra 0 is length is odd
if len(hexcode) & 1:
hexcode = "0"+hexcode
array = []
for i in range(0, len(hexcode), 2):
array.append('0x'+hexcode[i]+hexcode[i+1])
print(array)
['0x1', '0x7', '0xdd', '0x17']
方法二(使用to_bytes()方法):
我们还可以使用to_bytes(length,byteorder)方法将数字转换为十六进制字符串。但是这个函数的问题是,在打印时,十六进制代码可以转换为 ASCII 编码方案中的相应字符。为了克服这个问题,我们可以在这个方法上使用 hex() 方法。它需要两个参数,' length ' 是数组的大小,' byteorder'是字节的顺序,其中“ big”表示 MSB 在左边,“ little”表示 MSB 在右边。
下面是实现上述方法的代码:
蟒蛇3
import math
n = 543
# Calculate the length of array
size = int(math.log(n, 256))+1
# Use the method to_bytes() with "big"
# or "little" property We need to apply
# hex() method to avoid the conversion
# into ASCII letters
hexForm = n.to_bytes(size, "big").hex()
# Append 8 bits together ie pair of 4 bits to get a byte
array = []
for i in range(0, len(hexForm), 2):
array.append('0x'+hexForm[i]+hexForm[i+1])
print(array)
['0x02', '0x1f']
方法三(使用字符串格式化命令):
在Python中,有一个字符串命令“%x”可以将给定的整数转换为十六进制格式。我们可以使用它来获得所需的输出。
下面是实现上述方法的代码:
蟒蛇3
n = 8745
# Get string representation of hex code
hexcode = "%x" % n
# Pad an extra 0 is length is odd
if len(hexcode) & 1:
hexcode = "0"+hexcode
array = []
for i in range(0, len(hexcode), 2):
array.append('0x'+hexcode[i]+hexcode[i+1])
print(array)
['0x22', '0x29']