Bitwise Operators Explanation with Examples
Bitwise operators in Python manipulate individual bits of integers. They are useful in tasks such as low-level programming, cryptography, and optimization.
Bitwise Operators Overview
| Operator | Description |
|---|---|
& |
Bitwise AND - Sets each bit to 1 if both bits are 1. |
| |
Bitwise OR - Sets each bit to 1 if at least one bit is 1. |
^ |
Bitwise XOR - Sets each bit to 1 if only one of the bits is 1. |
~ |
Bitwise NOT - Inverts all the bits. |
<< |
Bitwise Left Shift - Shifts bits to the left, filling with zeros. |
>> |
Bitwise Right Shift - Shifts bits to the right, filling with zeros or sign bit. |
Examples
Bitwise AND (&) Example
Performing bitwise AND on integers 5 and 3:
- 5 (binary: 101)
- 3 (binary: 011)
Result of 5 & 3 is 1 (binary: 001).
Bitwise OR (|) Example
Performing bitwise OR on integers 5 and 3:
- 5 (binary: 101)
- 3 (binary: 011)
Result of 5 | 3 is 7 (binary: 111).
Bitwise XOR (^) Example
Performing bitwise XOR on integers 5 and 3:
- 5 (binary: 101)
- 3 (binary: 011)
Result of 5 ^ 3 is 6 (binary: 110).
Bitwise NOT (~) Example
Performing bitwise NOT on integer 5:
- 5 (binary: 000...000101)
Result of ~5 is -6 (binary: 111...111010 in 32-bit representation).
Bitwise Left Shift (<<) Example
Performing bitwise left shift on integer 5 by 1 position:
- 5 (binary: 101)
Result of 5 << 1 is 10 (binary: 1010).
Bitwise Right Shift (>>) Example
Performing bitwise right shift on integer 5 by 1 position:
- 5 (binary: 101)
Result of 5 >> 1 is 2 (binary: 10).
Bitwise AND (&) Example
Performing bitwise AND on integers 5 and 3:
- 5 (binary: 101)
- 3 (binary: 011)
Result of 5 & 3 is 1 (binary: 001).
Bitwise OR (|) Example
Performing bitwise OR on integers 5 and 3:
- 5 (binary: 101)
- 3 (binary: 011)
Result of 5 | 3 is 7 (binary: 111).
Bitwise XOR (^) Example
Performing bitwise XOR on integers 5 and 3:
- 5 (binary: 101)
- 3 (binary: 011)
Result of 5 ^ 3 is 6 (binary: 110).
Bitwise NOT (~) Example
Performing bitwise NOT on integer 5:
- 5 (binary: 000...000101)
Result of ~5 is -6 (binary: 111...111010 in 32-bit representation).
Bitwise Left Shift (<<) Example
Performing bitwise left shift on integer 5 by 1 position:
- 5 (binary: 101)
Result of 5 << 1 is 10 (binary: 1010).
Bitwise Right Shift (>>) Example
Performing bitwise right shift on integer 5 by 1 position:
- 5 (binary: 101)
Result of 5 >> 1 is 2 (binary: 10).