Python Bitwise Operators:
|We can use the PyCharm code editor for this example. If you do not know about it then follow this link- How to install PyCharm for Python and create a program in it.|
(1) Python provides bit manipulation operators to directly operate on the bits or binary numbers directly. When we use bitwise operators on the operands, the operands are firstly converted to bits and then the operation is performed on the bit directly. Bitwise operators are binary operators and unary operators that can be operated on two operands or one operand.
|&||AND||x & y||Bits that are set in both x and y are set|
||||OR||x | y||Bits that are set in either x or y are set.|
|^||XOR||x ^ y||Bits that are set in either x or y but not both are set.|
Truth Table: 1 = TRUE, 0 = FALSE
|x||y||x & y||x | y||x ^ y|
(2) Example of Bitwise & Operator.
- print (bin(x)) gives the binary number of x.
- print (bin(y)) gives the binary number of y.
- print (bin(x&y), x&y). bin(x&y) command compares the binary values of x and y. You can manually check it by using the truth table. x&y output is 12 because the binary value of 12 is 0b1100.
(3) Example of Bitwise | Operator.
(4) Example of Bitwise ^ Operator.