Language: EN

python-operadores-bitwise

Bitwise Operators in Python

Bitwise operators in Python allow manipulating the individual bits of integer numbers. They are useful for performing bit-level operations, such as shifting, AND, OR, XOR, and complement.

The bitwise operators in Python are as follows:

OperatorDescription
AND (&)Performs a bitwise AND operation
OR (|)Performs a bitwise OR operation
XOR (^)Performs a bitwise XOR operation
Left Shift (<<)Shifts bits to the left
Right Shift (>>)Shifts bits to the right
Complement (~)Returns the one’s complement of the number

AND Operator (&)

The AND operator (&) compares each bit of two operands and returns 1 if both bits are 1; otherwise, it returns 0.

# Example of AND operator
a = 10  # 1010 in binary
b = 3   # 0011 in binary
result = a & b
print(result)  # Output: 2
# Explanation: 1010 & 0011 = 0010 (decimal 2)

OR Operator (|)

The OR operator (|) compares each bit of two operands and returns 1 if at least one of the bits is 1.

# Example of OR operator
a = 10  # 1010 in binary
b = 3   # 0011 in binary
result = a | b
print(result)  # Output: 11
# Explanation: 1010 | 0011 = 1011 (decimal 11)

XOR Operator (^)

The XOR operator (^) compares each bit of two operands and returns 1 if exactly one of the bits is 1, but not both.

# Example of XOR operator
a = 10  # 1010 in binary
b = 3   # 0011 in binary
result = a ^ b
print(result)  # Output: 9
# Explanation: 1010 ^ 0011 = 1001 (decimal 9)

Shift Operators

Shift operators move the bits of a number to the left (<<) or to the right (>>) by the specified amount.

Left Shift Example

# Example of left shift
a = 5   # 101 in binary
result = a << 2
print(result)  # Output: 20
# Explanation: 101 << 2 = 10100 (decimal 20)

Right Shift Example

# Example of right shift
a = 20   # 10100 in binary
result = a >> 2
print(result)  # Output: 5
# Explanation: 10100 >> 2 = 101 (decimal 5)

Complement Operator (~)

The complement operator (~) inverts all the bits of a number.

# Example of complement operator
a = 5   # 101 in binary
result = ~a
print(result)  # Output: -6
# Explanation: ~101 = -110 (in two's complement, -6 in decimal)