Determining combination of bits
Larry Bates
lbates at syscononline.com
Mon Nov 8 15:23:56 EST 2004
You didn't say anything about how large the
numbers might get. If they stay small (e.g. <thousands)
you could just look them up directly from a dictionary.
If they can get arbitrarily large you must use bit
shifing and boolean & (and).
Sounds a lot like a homework assignment, but I'll
give you some "hints".
1) Use bit shifting operator (>>) and boolean &
operator to isolate each bit in the integer.
2) It will be either zero or one. Build up a
list of these which will represent the power
of two that each one bit represents.
Larry Bates
Sean Berry wrote:
> Say I have a dictionary like the following
>
> {1:'one',2:'two',4:'three',8:'four',16:'five', etc...}
>
> and I am given some numbers, say 22, 25, and 9. I want to determine the
> keys, powers of 2, that comprise the number.
>
> Ex. 22 = 16+4+2
> 25 = 16+8+1
> 9 = 8+1
> ...etc...
>
> How do I get these keys?
>
>
More information about the Python-list
mailing list