Before anything else: what are bitwise operators? Well, they allow us to manipulate individual bits within an integer. That might sound boring at first glance, but trust me when I say it’s anything but! With these bad boys in your toolkit, you can implement all sorts of cool algorithms like compression, encryption, and error detection (just to name a few).
So let’s take a look at some examples. First up is the bitwise AND operator (&), which returns a new integer with bits set to 1 only if both corresponding bits in the operands are also 1:
# Example usage of the bitwise AND operator (&)
# This operator compares the binary representation of two integers and returns a new integer with bits set to 1 only if both corresponding bits in the operands are also 1.
# Assigning values to variables a and b
a = 5 # binary representation: 0b101
b = 3 # binary representation: 0b0011
# Using the bitwise AND operator to compare the binary representation of a and b
result = a & b # binary result: 0b001
# Printing the binary representation of the result
print(bin(result)) # prints "0b100" (decimal value is 4)
Next up, we have the bitwise OR operator (|), which returns a new integer with bits set to 1 if either corresponding bit in the operands is 1:
# Example usage of the bitwise OR operator (|)
# The bitwise OR operator (|) returns a new integer with bits set to 1 if either corresponding bit in the operands is 1.
# Assigning integer value 5 to variable a
a = 5 # binary representation: 0b101
# Assigning integer value 3 to variable b
b = 3 # binary representation: 0b0011
# Using the bitwise OR operator to perform a bitwise OR operation on a and b
result = a | b # binary result: 0b1011
# Printing the binary representation of the result using the bin() function
print(bin(result)) # prints "0b1011" (decimal value is 11)
Finally, we have the bitwise XOR operator (^), which returns a new integer with bits set to 1 if exactly one corresponding bit in the operands is 1:
# Example usage of the bitwise XOR operator (^)
# The bitwise XOR operator (^) returns a new integer with bits set to 1 if exactly one corresponding bit in the operands is 1.
# Assigning integer values to variables a and b
a = 5 # binary representation: 0b101
b = 3 # binary representation: 0b0011
# Using the bitwise XOR operator to perform the operation on the two variables
result = a ^ b # binary result: 0b1001
# Printing the binary representation of the result using the bin() function
print(bin(result)) # prints "0b1001" (decimal value is 9)
Now, you might be wondering why anyone would want to use bitwise operators in the first place. Well, there are a few reasons! For one thing, they can help us optimize our code by reducing memory usage and improving performance. Plus, they’re just plain fun to play around with (trust me).
So go ahead give them a try! Who knows what kind of crazy algorithms you might come up with next?