bitwise operator, bits dont go into bitbucket..?

Chris Angelico rosuav at gmail.com
Tue Nov 10 17:33:38 EST 2015


On Wed, Nov 11, 2015 at 9:27 AM, kent nyberg <kent at z-sverige.nu> wrote:
> Im reading about bitwise operators and is it true to say they dont work 100% as in C?
> bitwise operators in C seem to result in bits going to the so called bitbucket.
> For example, 0b00000001. Shifting it >> 1  in C it seems to add on zero to the left and the 1 to the right gets throwned away.
>
> But doing it in python just adds one more bit, from the left.
> That is, 0b00000001 >> 1     = 0b000000001.

I'm not sure what you're expecting Python to do here, but
right-shifting the integer 1 results in the integer 0:

>>> 0b000001 >> 1
0

> Bitwise operators in C (when reading examples,) gives some time code that check specific bits by
> shifting the bits left and right to make every bit but the specific one to zeros.
> As I understand bitwise operators in python, this is not possible then?

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

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



More information about the Python-list mailing list