Changing an array of True and False answers to a hex value Python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 Question
00:58 Accepted answer (Score 7)
01:24 Answer 2 (Score 1)
01:44 Answer 3 (Score 1)
02:04 Answer 4 (Score 0)
03:03 Thank you
--
Full question
https://stackoverflow.com/questions/2558...
Question links:
http://pastebin.com/1839NKCx
Answer 2 links:
[reduce]: https://docs.python.org/2/library/functi...
[MSB]: http://en.wikipedia.org/wiki/Most_signif...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 Question
00:58 Accepted answer (Score 7)
01:24 Answer 2 (Score 1)
01:44 Answer 3 (Score 1)
02:04 Answer 4 (Score 0)
03:03 Thank you
--
Full question
https://stackoverflow.com/questions/2558...
Question links:
http://pastebin.com/1839NKCx
Answer 2 links:
[reduce]: https://docs.python.org/2/library/functi...
[MSB]: http://en.wikipedia.org/wiki/Most_signif...
--
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)