The Python Oracle

Changing an array of True and False answers to a hex value Python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands

--

Chapters
00:00 Changing An Array Of True And False Answers To A Hex Value Python
00:51 Answer 1 Score 1
01:07 Accepted Answer Score 8
01:33 Answer 3 Score 1
01:46 Answer 4 Score 0
01:54 Thank you

--

Full question
https://stackoverflow.com/questions/2558...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 8


lists = [
    [True, True, True, False, False, True, False, False],
    [True, True, False, False, True, False, False, True],
    [True, False, False, True, False, False, True, True],
    [False, False, True, False, False, True, True, True],
    [False, True, False, False, True, True, True, False],
    [True, False, False, True, True, True, False, False],
    [False, False, True, True, True, False, False, True],
    [False, True, True, True, False, False, True, False],
]

for l in lists:
    zero_one = map(int, l)  # convert True to 1, False to 0  using `int`
    n = int(''.join(map(str, zero_one)), 2)  # numbers to strings, join them
                                             # convert to number (base 2)
    print('{:02x}'.format(n))  # format them as hex string using `str.format`

output:

e4
c9
93
27
4e
9c
39
72



ANSWER 2

Score 1


No need for a two steps process if you use reduce (assuming MSB is at left as usual):

b = [True, True, True, False, False, True, False, False]
val = reduce(lambda byte, bit: byte*2 + bit, b, 0)

print val
print hex(val)

Displaying:

228
0xe4



ANSWER 3

Score 1


If you want to combine a series of boolean values into one value (as a bitfield), you could do something like this:

x = [True, False, True, False, True, False ]
v = sum(a<<i for i,a in enumerate(x))
print hex(v)



ANSWER 4

Score 0


This should do it:

def bool_list_to_hex(list):
  n = 0
  for bool in list:
    n *= 2
    n += int(bool)
  return hex(n)