Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to convert list to hex string [closed]

Tags:

python

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
like image 876
MalphasWats Avatar asked Dec 12 '22 13:12

MalphasWats


2 Answers

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
like image 89
millimoose Avatar answered Feb 13 '23 05:02

millimoose


>>> 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'
like image 34
arshajii Avatar answered Feb 13 '23 05:02

arshajii