Get and Set Bit Problem

In getBit bhaiya has done if(n&mask)>0 then 1 else 0.
Can’t we just put it return (n&i) ??

Hi,

No you cannot do that. Remember, i is the position of the bit which you have to check. Consider the case n=3 and i=2. n&i will be equal to 2. But the answer should be 1.

Ans if we don’t do (i<<i) and directly put return (n&i)>0?1:0 then also it will execute ??

No . Consider the case n=4 and i=3. n&i is 0 but the answer is 1. because third set bit of 4 is 1.

https://ide.codingblocks.com/s/220167 Why I am not getting for n=4 and i=3 is 1 ?

For getting 3rd set bit you should do 1<<2. Basically, you should do 1<<(i-1) to get i’th set bit. Because in 100(binary representation of 4) 0th set bit is 0 1st set bit is 0 and 2nd set bit is 1 because of zero based indexing. But if we take 1 based indexing then 1st bit is 0 second bit is 0 and third bit is 1.