Concept of Bit Manipulation using C++
Bit Manipulation is a very effective technique that is used to solve problems in optimized way. This technique is useful for competitive programming perspective.
Bit Manipulation in C++
Prerequisites: We should have knowledge of binary number system
Get ith bit:
Mask: Right shift n ‘i’ times, and check the first bit.
int getBit(int n,int pos){ return (n >> pos) & 1; }
Set ith bit:
Mask: 1 << i
Bitwise OR operation between n and mask sets the ith bit to one.
int setBit(int n, int pos){ return(n | (1 << pos)); }
Clear ith bit
Mask: ~ (1 << i )
In the mask, all the bits would be one, except the ith bit. Taking bitwise AND with n would clear the ith bit.
int clearBit(int n,int pos){ int mask=~(1 << pos); return (n & mask); }
Toggle ith bit
Mask: 1 << i
Bitwise XOR operation between n and mask toggle the ith bit.
int toggleBit(int n, int pos){ return (n xor (1 << pos)); }
Update i’th bit to the given value
Mask: mask has all the bits set to one except i
th bit.
n = n & mask, ith bit is cleared.Now, to set ith bit to value, we take value << pos as the mask.
int updateBit(int n,int pos,int value){ int mask=~(1 << pos); n=n & mask; return (n | (value << pos)); }
I hope you have got the concept of bit manipulation with the above example of C++ programming.
Leave a Reply