- Bitwise AND (
&
): Performs a bitwise AND operation on the corresponding bits of two operands. - Bitwise OR (
|
): Performs a bitwise OR operation on the corresponding bits of two operands. - Bitwise XOR (
^
): Performs a bitwise XOR (exclusive OR) operation on the corresponding bits of two operands. It returns 1 if the bits are different. - Bitwise NOT (
~
): Flips the bits of its operand. It's a unary operator. - Bitwise left shift (
<<
): Shifts the bits of the first operand to the left by the number of positions specified by the second operand. - Bitwise right shift (
>>
): Shifts the bits of the first operand to the right by the number of positions specified by the second operand.
# Define two integers
a = 10 # Binary representation: 1010
b = 6 # Binary representation: 0110
# Bitwise AND
print("Bitwise AND:", a & b) # Output: 2 (Binary representation: 0010)
# Bitwise OR
print("Bitwise OR:", a | b) # Output: 14 (Binary representation: 1110)
# Bitwise XOR
print("Bitwise XOR:", a ^ b) # Output: 12 (Binary representation: 1100)
# Bitwise NOT
print("Bitwise NOT of a:", ~a) # Output: -11 (Binary representation: ...11111111111111111111111111110101)
# Bitwise left shift
print("Bitwise left shift:", a << 1) # Output: 20 (Binary representation: 10100)
# Bitwise right shift
print("Bitwise right shift:", a >> 1) # Output: 5 (Binary representation: 0101)
四則運算
加法/減法
- Perform bitwise XOR (
^
) to get the sum without considering carry. - Perform bitwise AND (
&
) to get the carry. - Shift the carry to the left by one position.
- Add the result of step 1 and the shifted carry until the carry becomes zero.
def add(a, b):
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
# Example:
print(add(5, 3)) # Output: 8
乘法
Multiplication can be performed by repeated addition or by using bitwise shift operations.
def multiply(a, b):
result = 0
while b > 0:
if b & 1:
result = add(result, a)
a <<= 1
b >>= 1
return result
# Example:
print(multiply(5, 3)) # Output: 15
除法
Division can be performed by repeated subtraction or by using bitwise shift operations.
def divide(dividend, divisor):
quotient = 0
while dividend >= divisor:
dividend = subtract(dividend, divisor)
quotient = add(quotient, 1)
return quotient
# Example:
print(divide(15, 3)) # Output: 5