How do I access the bit at a particular index in a number using shift operator.
Say the number is $n$.
Let the index be $i (i: 0 \le i < n).$
Rightmost bit is $0$.
The only thing I can think of is:
$def \, bitAt(n, i)$
$\,\,\,\,\,\,\,\,m = n >> i+1$
$\,\,\,\,\,\,\,\,v = n >> i$
$\,\,\,\,\,\,\,\,m = m << 1$
$\,\,\,\,\,\,\,\,if(m == v)$
$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,return \, 0$
$\,\,\,\,\,\,\,\,else$
$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,return \, 1$
$\,\,\,\,\,\,\,\,end$
$end$
Is there a more efficient way to do this?
if ((n << i) & n) == 0 return 0 else return 1
. What this does is create a number with thei
th bit set to one, thenAND
this with the original number, if that bit is1
in the original number, the result isn << 1
, otherwise it becomes zero. $\endgroup$ – Mahdi Sep 30 '17 at 12:41((1 << i) & n) == 0
in the conditional,1 << i
sets thei
th bit to 1. $\endgroup$ – Mahdi Sep 30 '17 at 12:54