Determining combination of bits

Steven Bethard steven.bethard at gmail.com
Mon Nov 8 16:02:16 EST 2004


Sean Berry <sean <at> buildingonline.com> writes:
> 
> I am using two database tables.  One will have some options and a code 
> (power of 2).
> 
> Then, someone will check off checkboxes and submit.  The number will be 
> added and saved in a cookie.  Then, later, I want to be able to redisplay 
> their choices by reading the value from the cookie.

You might look at the number_in_base thread:

http://groups.google.com/groups?threadm=4186990d.1364093693%40news.oz.net

This gives a solution something like:

>>> def number_in_base(n, b=10, digits='0123456789ABCDEF'):
...     return '-'[:n<0]+''.join(reversed(list(
...         digits[r]                
...         for q in [abs(n)]
...         for q, r in iter(lambda: divmod(q, b), (0, 0))))) or digits[0]
... 
>>> digits = number_in_base(22, 2)
>>> [power_of_2
...  for power_of_2, digit
...  in zip(reversed([2**x for x in range(len(digits))]), digits)
...  if digit == '1']
[16, 4, 2]


Steve




More information about the Python-list mailing list