Bitwise Operators

Bitwise operators are used to perform operations on the binary representations of integers.

AND (&)

Performs a bitwise AND operation between two integers. Each bit in the result is set to 1 if both corresponding bits of the operands are 1, otherwise it is set to 0.

a = 12  # 1100 in binary
b = 7   # 0111 in binary
result = a & b  # 0100 in binary, which is 4 in decimal

OR (|)

Performs a bitwise OR operation between two integers. Each bit in the result is set to 1 if at least one of the corresponding bits of the operands is 1.

a = 12  # 1100 in binary
b = 7   # 0111 in binary
result = a | b  # 1111 in binary, which is 15 in decimal

XOR (^)

Performs a bitwise XOR operation between two integers. Each bit in the result is set to 1 if the corresponding bits of the operands are different, otherwise it is set to 0.

a = 12  # 1100 in binary
b = 7   # 0111 in binary
result = a ^ b  # 1011 in binary, which is 11 in decimal

NOT (~)

Performs a bitwise NOT operation on an integer. It inverts all the bits of the number. In Python, the result is also affected by Python's handling of negative numbers using two's complement notation.

a = 12  # 1100 in binary
result = ~a  # -1101 in binary, which is -13 in decimal

Left Shift (<<)

Shifts the bits of the first operand to the left by the number of positions specified by the second operand. Zeroes are shifted into the vacated positions.

a = 12  # 1100 in binary
result = a << 2  # 110000 in binary, which is 48 in decimal

Right Shift (>>)

Shifts the bits of the first operand to the right by the number of positions specified by the second operand. The behavior with regard to sign extension (filling in the vacated positions) can differ between positive and negative numbers.

a = 12  # 1100 in binary
result = a >> 2  # 0011 in binary, which is 3 in decimal

Python program that demonstrates the use of basic bitwise operators:

a = 60  # 0011 1100 in binary
b = 13  # 0000 1101 in binary

print("a & b =", a & b)  # 12 (0000 1100 in binary)
print("a | b =", a | b)  # 61 (0011 1101 in binary)
print("a ^ b =", a ^ b)  # 49 (0011 0001 in binary)
print("~a =", ~a)        # -61 (inverted bits, sign-extended)
print("a << 2 =", a << 2)  # 240 (1111 0000 in binary)
print("a >> 2 =", a >> 2)  # 15 (0000 1111 in binary)       
What Are People Saying About Us

Read These Life Changing Stories From People Just Like You!