gpt4 book ai didi

python - 在python 3中将十六进制转换为数组内的bin

转载 作者:行者123 更新时间:2023-12-01 01:30:48 27 4
gpt4 key购买 nike

我正在 Visual Studio 上研究 Python 项目。我有一个数组和用户输入,用于将十六进制转换为十进制,将十进制转换为二进制。我在我的项目中使用它们(十六进制,十进制,二进制)。这是我的代码的基本示例:

dynamicArrayBin = [ ]
dynamicArrayHex = [ ]
hexdec = input("Enter the hex number to binary ");
dynamicArrayHex = [hexdec[idx:idx+2] for idx in range(len(hexdec)) if idx%2 == 0]
binary = '{:08b}'.format(int(dynamicArrayHex[0] , 16))

因此,当用户输入01进行输入时,代码会给出00000001。我想将元素 0 0 0 0 0 0 0 1 的结果分开并放入 dynamicArrayBin=[] 中。过了一会儿,当我调用 dynamicArrayBin=[0] 时,它应该显示 0

有什么办法吗?

最佳答案

如果您想要十六进制输入的二进制数字列表,则无需首先将输入拆分为字节(这就是您的代码当前所做的,将十六进制输入的每 2 个字符转换为覆盖该范围的整数0-255)。

只需将整个十六进制输入转换为整数,然后将其格式化为二进制:

integer_value = int(hexdec, 16)
byte_length = (len(hexdec) + 1) // 2 # to help format the output binary
binary_representation = format(integer_value, '0{}b'.format(byte_length * 8))

binary_representation 值是一个由 '0''1' 字符组成的字符串,并且由于字符串是序列,因此不需要将其转换为列表,除非您必须能够改变单个字符。

所以:

print(binary_representation[0])

工作并打印01

如果您必须有一个列表,可以使用 list(binary_representation)) 来实现。

演示:

>>> hexdec = 'deadbeef'  # 4 bytes, or 32 bits
>>> integer_value = int(hexdec, 16)
>>> byte_length = (len(hexdec) + 1) // 2 # to help format the output binary
>>> binary_representation = format(integer_value, '0{}b'.format(byte_length * 8))
>>> integer_value
3735928559
>>> byte_length
4
>>> binary_representation
'11011110101011011011111011101111'
>>> binary_representation[4]
'1'
>>> binary_representation[2]
'0'
>>> list(binary_representation)
['1', '1', '0', '1', '1', '1', '1', '0', '1', '0', '1', '0', '1', '1', '0', '1', '1', '0', '1', '1', '1', '1', '1', '0', '1', '1', '1', '0', '1', '1', '1', '1']

如果您想要的只是十六进制值的第一位,那么有一个更快的方法:

if len(hexdec) % 2:  # odd number of hex characters, needs a leading 0
hexdec = '0' # doesn't matter what the rest of the hex value is
print('1' if hexdec[0].lower() in '89abcdef' else '0')

因为二进制表示的前 4 位完全由第一个十六进制字符确定,并且第一个位设置为十六进制值 8F

关于python - 在python 3中将十六进制转换为数组内的bin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52891540/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com