3. ith bit #
Created Monday 29 June 2020
- Return ith bit.
A simple way to do this would be
N = 100010101 // suppose we need 2nd bit - zero based counting
Approach 1 - Shift+Modulus:
- Shift by k to the right
- Check last bit
return (n >> i)%2; // Booth's algorithm - O(n)
Approach 2 - Shift and AND: We can produce pow(2, i) using the left shift operator
return (n >> i) & 1; // returns 1 if set and 0 if unset
---- #
- Set ith bit - OR
// 01101 to set 2nd bit we need 00100 i.e 2^i
// to set we use OR
n|=(1<<i); // O(1)
---- #
- Unset ith bit - AND and NOT
// the
n&=~(1<<i);