Related Tags

bitwise
python
operators

# What are bitwise operators in Python?

Bitwise operators are used to perform bitwise operations on binary patterns. These operators work efficiently. All the binary operators are in-fix except for the not operator.

## Types of bitwise operators

operator description example
& (AND) The bits that are set in both operands are set. (10101010) & (11111111) = (10101010)
| (OR) The bits that are set in either of the two operands are set. (10101010) | (11111111) = (11111111)
^ (XOR) he bits that are set in only one, not both, or the operands are set. (10101010) ^ (11111111) = (01010101)
~ (NOT) Its unary operator, and the bits that are set, will be unset. ~ (10101010) = (01010101)
<< (SHIFT LEFT) It shift the bits of operand1 operand2 times to the left (10101010) << (00000011) = (01010000)
>> (SHIFT RIGHT) It shift the bits of operand1 operand2 times to the right (10101010) >> (00000011) = (00001010)

### Example

In the below output 0b is used to represent the binary number.

# assignment operators
x = 12 # (00001100)
y = 6  # (00000110)

# The bin() function is used to print in binary format.

print ('x =', x ,' and y =',y)
# and operator
print ('x & y is equal to', bin(x & y))
# or operator
print ('x | y is equal to', bin(x | y))
# xor operator
print ('x ^ y is equal to', bin(x ^ y))
# shift left operator
print ('x << y is equal to', bin(x << y))
# shift right operator
print ('x >> y is equal to', bin(x >> y))
# not operator
print ('~ x is equal to', bin(~ x ))

RELATED TAGS

bitwise
python
operators