Python Bitwise Operator
Bitwise Operators in Python.
The binary numbers are compared using these operators.We can perform different operations on binary numbers such as and, or, xor, not, left shift, and right shift.These operators are also often called bitwise-or, bitwise-and, and bitwise-xor, etc.Shift operators are used to shifting the values of the binary number to left or right.
Bitwise Operator in Python
Bitwise Operators are used to manipulate individual bits of integers. Python provides several bitwise operators that perform operations at the bit level. All Bitwise operators in python are discussed below in detail with their syntax and proper example:
1. AND (&)
It returns 1 if both the bits are 1 else it returns 0
Syntax
bit1 & bit2
Example
>>> a = 1 >>> b = 1 >>> a & b 1 >>> a=101
>>> b=111
>>> a & b 101
2. OR ( | )
It returns 0 only if both the bits are zero else it returns 1.
Syntax
bit1 | bit2
Example
>>> a = 0 >>> b = 0 >>> a | b 0 >>> a=100 >>> b=110 >>> a | b 110
3. XOR ( ^ )
It returns 1 only if one of the both the bits is 1 else it returns 0.
Syntax
bit1 ^ bit2
Example
>>> a = 0 >>> b = 0 >>> a ^ b 0 >>> a=11 >>> b=110 >>> a ^ b 101
4. NOT (~)
It inverts all the bits.
Syntax
~ bit
Example
>>>a = 5
>>>~a
-6
5. Left shift ( << )
It pushes 0’s from right and let the left most bit fall off for each and every 0.
Syntax
bit << key
Example
>>>a = 10
>>>a<<1
20
5. Right shift ( >> )
It pushes 0’s from left and let the right most bit fall off for each and every 0.
Syntax
bit >> key
Example
>>>a = 10
>>>a>>1 5
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment