In Python, bitwise operators are used to perform operations on individual bits of binary representations of numbers. These operators work at the bit level and manipulate the binary digits of integers. Python provides the following bitwise operators:

  1. Bitwise AND (&): It performs a bitwise AND operation between the corresponding bits of two integers. Each bit of the result is set to 1 only if both bits are 1. Example: 5 & 3 returns 1 (binary 0101 & 0011 = 0001).

  2. Bitwise OR (|): It performs a bitwise OR operation between the corresponding bits of two integers. Each bit of the result is set to 1 if at least one of the bits is 1. Example: 5 | 3 returns 7 (binary 0101 | 0011 = 0111).

  3. Bitwise XOR (^): It performs a bitwise XOR (exclusive OR) operation between the corresponding bits of two integers. Each bit of the result is set to 1 if the two bits are different. Example: 5 ^ 3 returns 6 (binary 0101 ^ 0011 = 0110).

  4. Bitwise NOT (~): It performs a bitwise negation operation on an integer. It flips all the bits, converting 0s to 1s and 1s to 0s. The result is the two’s complement of the number. Example: ~5 returns -6 (binary ~0101 = 1010, which is the two’s complement representation of -6).

  5. Left Shift (<<): It shifts the bits of the left operand to the left by the number of positions specified by the right operand. Zeros are shifted in from the right. Example: 5 << 2 returns 20 (binary 0101 << 2 = 010100, which is equivalent to decimal 20).

  6. Right Shift (>>): It shifts the bits of the left operand to the right by the number of positions specified by the right operand. In a right shift, the leftmost bit is filled with the sign bit (0 for non-negative numbers, 1 for negative numbers). Example: 11 >> 1 returns 5 (binary 1011 >> 1 = 0101, which is equivalent to decimal 5).

These bitwise operators are commonly used in low-level programming, optimization, and working with binary data. They allow you to manipulate individual bits and perform operations at a very fine-grained level.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

%d