Python将十六进制字符串转换为布尔数组

时间:2015-06-26 01:40:44

标签: python

我有一个十六进制字符串,如下所示: '\x00\x00\x00\x00\'

在上面的例子中,我希望在数组中得到8 * 8 = 64个布尔值。我该怎么做?

unhexlify会出现以下错误:

  

找到非十六进制数字

1 个答案:

答案 0 :(得分:0)

如果我正确理解你的问题,这应该会为你提供你正在寻找的布尔值列表:

text = "\\x00\\x00\\x00\\x00"

# First off, lets convert a byte represented by a string consisting of two hex digits
# into an array of 8 bits (represented by ints).
def hex_byte_to_bits(hex_byte):
    binary_byte = bin(int(hex_byte, base=16))
    # Use zfill to pad the string with zeroes as we want all 8 digits of the byte.
    bits_string = binary_byte[2:].zfill(8)
    return [int(bit) for bit in bits_string]

# Testing it out.
print(hex_byte_to_bits("00")) # [0, 0, 0, 0, 0, 0, 0, 0]
print(hex_byte_to_bits("ff")) # [1, 1, 1, 1, 1, 1, 1, 1]

# Use our function to convert each byte in the string.
bits = [hex_byte_to_bits(hex_byte) for hex_byte in text.split("\\x") if hex_byte != ""]
# The bits array is an array of arrays, so we use a list comprehension to flatten it.
bits = [val for sublist in bits for val in sublist]

print(bits) # [0, 0, 0, 0, ...

booleans = [bool(bit) for bit in bits]

print(booleans) # [False, False, False, ...