Bit Manipulation

Sep 18, 2020 By Puneet verma

Bitwise Operators
OR(|)
AND(&)
XOR(^)

Sno.  x y X|Y X&Y X^Y
1 0 0 0 0 0
2 0 1 1 0 1
3 1 0 1 0 1
4 1 1 1 1 0

Not or Complement(~)

2 s complement(2^n) = 1s complement + 1

sno x ~x 2^n
1 0 1 0
2 1 0 1


Right Shift Operator( >>)

A >> x

implies shifting the bits of A to the right by x positions. The last x bits are lost this way.

A >> x is equal to division by pow(2, x)

Example

0011101 >> 2 = 0000111

29>>2 = 29/pow(2,2) = 7 (integer value)

 

Left Shift Operator(<<)

A << x

implies shifting the bits of A to the left by x positions. The first x bits are lost this way. The last x bits have 0.

A << x is equal to multiplication by pow(2, x)

Example

0011101 << 2 = 1110100
29<<2 = 29*pow(2,2)= 116

 

Tricks of bits

Multiplication

17n = 16n+n = n *  pow(2,4) +n = (n << 4) + n

7n  =  8n -n = n * pow(2,3) - n = (n << 3) - n

54n = 64n -10n  = n * pow(2,6) - 10n = (n << 6) - 10n

 

for two number multiplication

read and write here

https://stackoverflow.com/questions/3722004/how-to-perform-multiplication-using-bitwise-operators

 

 

Practice these questions

https://www.geeksforgeeks.org/bitwise-algorithms/