November 21, 2024

Tirth's Blog

My technical notes

Python Bitwise Operators

Python provides the following bitwise operators:

  1. Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits of two integers. The result is 1 if both bits are 1; otherwise, it’s 0.
  2. Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two integers. The result is 1 if at least one of the bits is 1; otherwise, it’s 0.
  3. Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on the corresponding bits of two integers. The result is 1 if the bits are different; otherwise, it’s 0.
  4. Bitwise NOT (~): Performs a bitwise negation operation on a single integer. It flips all the bits, converting 1s to 0s and vice versa.
  5. Left Shift (<<): Shifts the bits of the first operand to the left by the number of positions specified by the second operand. Zeros are filled in on the right.
  6. Right Shift (>>): Shifts the bits of the first operand to the right by the number of positions specified by the second operand. If the number is positive, zeros are filled in on the left. If the number is negative, ones are filled in on the left.

Here’s an example demonstrating the usage of these operators:

# Bitwise AND (&)
a = 5    # Binary: 0101
b = 3    # Binary: 0011
result = a & b   # Binary: 0001
print(result)    # Output: 1

# Bitwise OR (|)
a = 5    # Binary: 0101
b = 3    # Binary: 0011
result = a | b   # Binary: 0111
print(result)    # Output: 7

# Bitwise XOR (^)
a = 5    # Binary: 0101
b = 3    # Binary: 0011
result = a ^ b   # Binary: 0110
print(result)    # Output: 6

# Bitwise NOT (~)
a = 5    # Binary: 0000 0101
result = ~a      # Binary: 1111 1010
print(result)    # Output: -6

# Left Shift (<<)
a = 5    # Binary: 0000 0101
result = a << 2  # Binary: 0001 0100
print(result)    # Output: 20

# Right Shift (>>)
a = 20   # Binary: 0001 0100
result = a >> 2  # Binary: 0000 0101
print(result)    # Output: 5

Remember that the bitwise operators work with integers and operate on the binary representation of those integers.

About The Author

Leave a Reply

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

Copyright © All rights reserved. | Newsphere by AF themes.