-1

I have a hex string that looks like: '\x00\x00\x00\x00\'

In the example above, I want to get 8*8= 64 boolean falses in an array. How do I do that?

unhexlify gives the following error:

Non-hexadecimal digit found

Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
Jessica
  • 721
  • 1
  • 6
  • 13
  • if you want it in hex, use `'\x00\x00\x00\x00\'.encode('hex')` – Jakob Weisblat Jun 26 '15 at 02:12
  • 1
    @JakobWeisblat: That's not what OP wants at all. They want `[False] * 32` (not 64 as the OP actually says, because it's 8 * 4). – Kevin Jun 26 '15 at 02:22
  • @Kevin it's 16 * 4, no? OP was thinking 8 octal digits, probably – cxrodgers Jun 26 '15 at 02:33
  • @PyDumb: first remove the backslash before the endquote from your string. Then use Jakob Weisblat's suggestion to convert to a hex string, and then see: http://stackoverflow.com/questions/1425493/convert-hex-to-binary – cxrodgers Jun 26 '15 at 02:34
  • @cxrodgers: We have 4 bytes, each of which is 8 bits. That's 32 bits in total. I don't see where you get 16. – Kevin Jun 26 '15 at 02:35

1 Answers1

0

If I'm understanding your question correctly, this should get you the list of booleans you're looking for:

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, ...
Beebs
  • 21
  • 4