Skip to content

Python bitwise operators

  • by

Python Bitwise operators are used to compare (binary) numbers. Python’s bitwise operators only work with integers.

OperatorMeaningExampleDescription
&Bitwise ANDx & y = 0 (0000 0000)Sets each bit to 1 if both bits are 1
|Bitwise ORx | y = 14 (0000 1110)Sets each bit to 1 if one of the two bits is 1
~Bitwise NOT~x = -11 (1111 0101)Inverts all the bits
^Bitwise XORx ^ y = 14 (0000 1110)Sets each bit to 1 if only one of two bits is 1
>>Bitwise right shiftx >> 2 = 2 (0000 0010)Shift left by pushing zeros in from the right and let the leftmost bits fall off
<<Bitwise left shiftx << 2 = 40 (0010 1000)Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

The values are first converted to binary, and then manipulations are done bit by bit, hence the phrase “bitwise operators.” The outcome is then displayed in decimal numbers.

Every binary bitwise operator has a compound operator that performs an enhanced application.

OperatorSyntaxEquivalent to
&=N1 &= N2N1 = N1 & N2
|=N1 |= N2N1 = N1 | N2
^=N1 ^= N2N1 = N1 ^ N2
<<=N1 <<= nN1 = N1 << n
>>=N1 >>= nN1 = N1 >> n

Python bitwise operators

Simple example code.

a = 60  # 60 = 0011 1100
b = 13  # 13 = 0000 1101
c = 0

c = a & b  # 12 = 0000 1100
print("& Value of c is ", c)

c = a | b  # 61 = 0011 1101
print("| Value of c is ", c)

c = a ^ b  # 49 = 0011 0001
print("^ Value of c is ", c)

c = ~a  # -61 = 1100 0011
print("~ Value of c is ", c)

c = a << 2  # 240 = 1111 0000
print("<< Value of c is ", c)

c = a >> 2  # 15 = 0000 1111
print(">> Value of c is ", c)

Output:

Python bitwise operators

Do comment if you have any doubts or suggestions on this Python operator topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *