If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, bitwise operators are used to perform operations on individual bits of integers. These operators work at the binary level, manipulating the bits of numbers. Bitwise operators are useful when you need to work with low-level data representation and perform bitwise manipulations. There are six bitwise operators in Python:
- Bitwise AND:
&
Performs a bitwise AND operation between corresponding bits of two integers. Each bit in the result is set to 1 only if both corresponding bits in the operands are 1.Example:
pythonCopy code
a = 10 # Binary: 1010 b = 7 # Binary: 0111 result = a & b print(result) # Output: 2 (Binary: 0010)
- Bitwise OR:
|
Performs a bitwise OR operation between corresponding bits of two integers. Each bit in the result is set to 1 if at least one corresponding bit in the operands is 1.Example:
pythonCopy code
a = 10 # Binary: 1010 b = 7 # Binary: 0111 result = a | b print(result) # Output: 15 (Binary: 1111)
- Bitwise XOR:
^
Performs a bitwise XOR (exclusive OR) operation between corresponding bits of two integers. Each bit in the result is set to 1 if the corresponding bits in the operands are different.Example:
pythonCopy code
a = 10 # Binary: 1010 b = 7 # Binary: 0111 result = a ^ b print(result) # Output: 13 (Binary: 1101)
- Bitwise NOT:
~
Performs a bitwise NOT operation on an integer, inverting all its bits. This operator is unary, meaning it works on a single operand.Example:
pythonCopy code
a = 10 # Binary: 1010 result = ~a print(result) # Output: -11 (Binary: 1111 0101)
- Bitwise Left Shift:
<<
Shifts the bits of an integer to the left by the specified number of positions. Zeros are added to the right.Example:
pythonCopy code
a = 5 # Binary: 0101 result = a << 2 print(result) # Output: 20 (Binary: 10100)
- Bitwise Right Shift:
>>
Shifts the bits of an integer to the right by the specified number of positions. Zeros are added to the left.Example:
pythonCopy code
a = 20 # Binary: 10100 result = a >> 2 print(result) # Output: 5 (Binary: 0101)
Bitwise operators are particularly useful in scenarios where you need to manipulate individual bits or perform binary-level operations. They are commonly used in embedded systems, networking protocols, and other low-level programming tasks.
Comments: 0