Newbie. Sorry for lame question.
I want to use each bit in an int (binary number) as a boolean.

In essence (this is c"ish" pseudocode):

bitVal = 0x01F; // 32-bit value

for(i=0; i <LIST_SIZE; i++){
     if(bitVal[i] == 1)
          printf(List[i])
}

So, for Python, I just need to know how to access each bit in the hex value.

UPDATE:
I think i found the way, using bit masking.

Recommended Answers

All 3 Replies

Like this for example (this example destroys the content of bitVal, so it should be for example function parameter or copy of one element of array)

bitVal = 0x01F


## takes Truth values from lsb to msb (least significant bit to most siginificant)
while bitVal>0:
    if bitVal & 1:print True
    else: print False
    bitVal= bitVal >> 1

To access given bit (2**bit):

def bit(n,x):
    return 1<<n & x and 1 or 0

Shorter (in spirit of C conciseness)

bitVal = 0x01F

## takes Truth values from lsb to msb (least significant bit
## to most siginificant)
while bitVal>0: print bitVal & 1 and True ; bitVal= bitVal >> 1

Awesome. Thank you. I have a long road ahead ;)

That
or 0
is actually not needed as x or 0 is x.
It is there only as logic looks little clearer for me that way.
X and then or else
is also replacement of ternary ?:
X ? then : else

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.