# Bitwise Operators in Python

October 26, 2020

I have seen bitwise operators in all programming language which I have used so far. Bitwise operators are used to do binary operation in the program. There are six bitwise operators in Python.

Now, let’s see the bitwise operators in Python:

Operator | Name | Description |
---|---|---|

& | AND | Sets each bit to 1 if both bits are 1 |

| | OR | Sets each bit to 1 if one of two bits is 1 |

^ | XOR | Sets each bit to 1 if only one of two bits is 1 |

~ | NOT | Inverts all the bits |

<< | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off |

>> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |

Python example with bitwise operators:

m =10 #"1010" n =7 #"0111" print("m AND n Operation:",m&n) #0010=2 print("m OR n Operation:",m|n) #1111=15 print("Before Left Shift Operation m:",m)#1010 print("After Left Shift Operation m:",(m<<2)&15)#0100=8 Output:

m AND n Operation: 2 m OR n Operation: 15 Before Left Shift Operation m: 10 After Left Shift Operation m: 8

In this tutorial, I have shown bitwise operators in Python. Hope you have enjoyed the tutorial. If you want to get updated, like my facebook page http://www.facebook.com/freetechtrainer and stay connected.