Bit Manipulation

on/off

  • 12 : 1100 - 5 : 0101 = 0111

    • inverse bits of 5 : 1010 and add 1 : 1011

    • 1100+1011 = 0111 = 7

  • & : AND

  • | : OR

  • ^ : XOR

  • ~ : inverse

  • >> : right shift | a>>1; divide by 2

  • << : left shift | a<<1; multiple by 2

  • bitwise OR is sum of 2 number

    • a = 5 (101) and b = 2 (010)

    • a|b = 111 which is 7 : if no carry is involved

    • is carry is there, then a|b + a&b

Divide and Multiply

int a = 6;
int ans1 = a << 1;
int ans2 = a >> 1;
cout << ans1 << " " << ans2 << endl;

Check if the kth bit is set or not

Check If The Number is Odd or Even

To swap two numbers

Check if a number is a power of 2

Count set bits

Find the odd occuring element

Last updated