Python Operators
Estimated reading: 2 minutes 268 views

Python Bitwise Operators – AND, OR, XOR, NOT Explained


What Are Bitwise Operators?

Bitwise operators in Python are used to perform operations on binary representations of integers. These operators manipulate individual bits, making them useful for tasks such as:

  • Hardware programming
  • Data compression
  • Cryptography
  • Flag masking and toggling

Bitwise Operators Table

OperatorNameSymbolExampleBinary Result
ANDBitwise AND&5 & 30b0101 & 0b0011 = 0b0001
ORBitwise OR```5
XORBitwise XOR^5 ^ 30b0101 ^ 0b0011 = 0b0110
NOTBitwise NOT~~5~0b0101 = -0b0110
Left ShiftShift Left<<5 << 10b0101 << 1 = 0b1010
Right ShiftShift Right>>5 >> 10b0101 >> 1 = 0b0010

Bitwise Examples in Python

AND &

a = 5        # 0b0101
b = 3        # 0b0011
print(a & b) # Output: 1 (0b0001)

OR |

print(a | b) # Output: 7 (0b0111)

XOR ^

print(a ^ b) # Output: 6 (0b0110)

NOT ~

print(~a)    # Output: -6 (two's complement of 5)

Shift Left <<

print(a << 1) # Output: 10 (0b1010)

Shift Right >>

print(a >> 1) # Output: 2 (0b0010)

Binary Display with bin()

You can visualize the binary version of numbers using bin():

print(bin(5))    # '0b101'
print(bin(~5))   # '-0b110'

Use Cases

  • Masking bits: flags = 0b1010 mask = 0b0100 print(flags & mask) # Check if 3rd bit is set
  • Setting a bit: flags |= 0b0001
  • Clearing a bit: flags &= ~0b0010
  • Toggling a bit: flags ^= 0b1000

Bitwise vs Logical Operators

TypeOperatorUse Case
Logicaland, orBoolean conditions
Bitwise&, `, ^`

Bit Length Utility

Use bit_length() to get how many bits are needed:

x = 99
print(x.bit_length())  # Output: 7

Same as len(bin(x)) - 2.


Summary Table

OperatorPurposePython ExampleResult (Decimal)
&Bitwise AND5 & 31
``Bitwise OR`5
^Bitwise XOR5 ^ 36
~Bitwise NOT~5-6
<<Shift left5 << 110
>>Shift right5 >> 12

FAQs – Bitwise Operators in Python

What’s the difference between & and and in Python?

& is bitwise AND for integers. and is a logical operator for boolean expressions.

Why is ~5 equal to -6?

Because Python uses two’s complement. ~x = -(x + 1).

Can you use bitwise operators on floats?

No. Bitwise operators work only with integers.

What happens if you shift bits beyond their width?

Python integers have arbitrary precision, so shifts won’t overflow, but may lead to large numbers.


Share Now :
Share

Bitwise Operators

Or Copy Link

CONTENTS
Scroll to Top