# Python Bitwise Operators

## Overview

Python bitwise operators work on bits and perform bit-by-bit operations. Bitwise operators are used in low-level programming for developing device drivers and embedded systems. They are also used in performance-critical code due to their speed. They require an understanding of the binary number system.

## Python Bitwise Operators

Python provides several bitwise operators that are used to perform operations on binary numbers (bits).

Python Operator |
Name |
Description |

& |
Binary AND | The operator sets the bit to the result if it exists in both operands. This operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, it is set to 0. |

| |
Binary OR | It sets the bit if it exists in either operand. This operator compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, it is set to 0. |

^ |
Binary XOR | This operator is used to compare two bits. If the corresponding bits are different, the result is 1. If they are the same, the result is 0. It sets the bit if it is set in one operand but not both. |

~ |
Binary NOT(Binary Ones Complement) | It is unary and has the effect of flipping bits. This is a unary operator that inverts all the bits of the operand. Essentially, 0 becomes 1, and 1 becomes 0. |

<< |
Binary Left Shift | The left operand value is moved left by the number of bits specified by the right operand. This operator shifts the bits of the first operand to the left by the number of positions specified by the second operand. New bits on the right are filled with 0. |

>> |
Binary Right Shift | The left operand value is moved right by the number of bits specified by the right operand. This operator shifts the bits of the first operand to the right by the number of positions specified by the second operand. For positive numbers, new bits on the left are filled with 0. For negative numbers, the behavior is implementation-specific. |

## Examples

Assume if x = 45 and y=12.

In the binary representation format, their values will be

0010 1101 and 0000 1100, respectively.

*# Python Bit-wise Operators*

*x = 45 # 0010 1101*

*y = 12 # 0000 1100*

**Bit-wise AND operator**

*z = x & y*

*print(z)# 0000 1100*

*12*

*# 12 in binary format is 0000 1100*

**Bit-wise OR operator **

*z = x | y*

*print(z) # 0010 1101*

*45*

—

## Python Tutorials

Python Tutorial on this website can be found at:

https://www.testingdocs.com/python-tutorials/

More information on Python is available at the official website: