Bitwise operators are most important in competitive programming.

Bitwise operators execute faster than arithmetic operators.
The following are the Bitwise operators we have. we look into them one by one.

 Bitwise AND

let us develop a code to give even numbers from a set of numbers using Bitwise AND

n = int(input('give the number'))
for i in range(1,n+1):
    if i&1 == 0:
        print(i,"odd ")
    else:
        print(i,"even")

In the above case 'i' and 1 are converted into binary numbers and the '&' condition is applied.

for example:

1&1 => 01& 01 = 01 (even)
     

2&1 = > 10 & 01 = 00 (odd)

Bitwise OR

print numbers which are divided by 3 or 5 in a range of numbers using bitwise or

n = int(input('give the number'))
for i in range(1,n+1):
    if i%3 == 0 | i%5 == 0:
        print(i,"divisible by 3 or 5 ")
    else:
        print(i,"not divisible by 3 or 5")

Bitwise XOR


Swap two numbers using XOR

a=5    # a = 101
b=6   # b = 110

a = a^b  #101 ^ 110 = 011
b = a^b  #011 ^ 110 = 101
a = a^b  #011 ^ 101 = 111
print(a,b)

Left shift

Left shift is used for multiplication


multiply a number with a power of 2

x = int(input('enter the number'))

print(x << 2) # 16 * 2 power 2

Right shift

The right shift is used for division

divide a number with a power of 2

x = int(input('enter the number'))

print(x >> 3) # 16 % 2 power 3