bitwise operator, bits dont go into bitbucket..?

kent nyberg kent at z-sverige.nu
Tue Nov 10 17:56:27 EST 2015


On Wed, Nov 11, 2015 at 09:33:38AM +1100, Chris Angelico wrote:
> On Wed, Nov 11, 2015 at 9:27 AM, kent nyberg <kent at z-sverige.nu> wrote:

> 
> If you want to check specific bits (in C or Python, either way), it's
> much more common to use bitwise AND than bit shifts:
> 
> >>> 0b100011011101010110 & 0b000000010000
> 16
> >>> print(bin(_))
> 0b10000
> 

So, to check if 0b010[this one bit]010 is set,   i do   & 0b0001000

That is,  I set just that one to 1 in the other and then the & operator will make it return
0 if its not set. Since every other is zero, the return will be zero if its not. Since & operator sets 0
if not both are 1. Right?  

Id so, Thanks.   

My misunderstanding was that
0b01000   (for example,) first could be shifted left. To become 0b10000.
And then shifted right to become 0b00001. 
The shifting would turn every other digit to 0 and leave only the wanted one untouched. 
That way, I could check if its 0 or 1.  If you understand my own logic of how it works.
But I got it wrong,  and I think I know how to do it with & operator.

> This will be either the same number as the right hand side (if the bit
> had been set) or zero (if it hadn't).
> 
> ChrisA
> -- 
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list