I have a long list that looks like this:
[True, True, True, False, ... ]
Representing walls in a tile map. It isn't guaranteed to be a multiple of 4 long, but it doesn't matter if it gets padded at the end.
I'd like to convert this into a hex string, so for the above example it would start with E ...
I was hoping there was a nice elegant way to do this (using Python 2.7.3)!
Thanks.
EDITED
This is an example of a 9x9 map:
map = [True, True, True, True,
True, True, True, True,
True, True, True, True,
True, False, False, True,
True, True, True, True,
True, False, False, False,
False, True, True, True,
True, True, False, False,
False, False, True, True,
True, True, True, True,
False, False, True, True,
True, True, True, True,
True, True, True, True,
True, True, True, True,
True, True, True, True,
True, True, True, True,
True, True, True, True,
True, True, True, True,
True, True, True, True,
True, True, True, True,
True]# False, False, False padded
what I would like is to be able to
str = heximify(map)
print str
> FFF9F87C3F3FFFFFFFFF8
Joining the one-liners club, by way of bit manipulation which seems more appropriate.
val = hex(reduce(lambda total, wall: total << 1 | wall, walls, 0))
This does the same as:
val = 0
for wall in walls:
val <<= 1 # add one 0 bit at the "end"
val |= wall # set this bit to 1 if wall is True, otherwise leave it at 0
val = hex(val) # get a hex string in the end
val = format(val, 'x') # or without the leading 0x if it's undesired
>>> walls = [True, True, True, False]
>>> hex(int(''.join([str(int(b)) for b in walls]), 2))
'0xe'
or (inspired by @millimoose's answer),
>>> hex(sum(b<<i for i,b in enumerate(reversed(walls))))
'0xe'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With