Mathematically get $n$th bit from integer

4.1k Views Asked by At

Most programming languages have functions for getting bits but I need to do it on a calculator so I need to understand how to do it mathematically. Basically I need a formula for getting the $n$th bit from and integer, $i$.

So given: $i = 6$ and $n = 3$, I would get $1$ because binary for $6$ is $110$.

How might I manage this?

3

There are 3 best solutions below

0
On BEST ANSWER

Given $i$ you want to throw away the bottom $n-1$ bits, so integer divide by $2^{n-1}$. Then take $\bmod 2$ to get the low order bit.

0
On

Most calculators have a way to truncate fractions. So to get bit #3 here are the steps

  1. Divide $i$ by $2^{n}$ and truncate the fractional part
  2. Divide the quotient by $2$ and take the remainder, i.e. check if it is odd or even

Example: Find the bit #5 of $111$.

$$2^5=32$$ So $$ 111/32=3.46875 $$ The truncated value is $3$. Now, $3$ divided by $2$ leaves $1$ as remainder (odd number). So bit #5 is $1$.

Repeat for bit #4. $$ 2^4=16$$. So $$ 111/16 = 6.9375 $$ Truncated answer is $6$ which is even. So bit #4 is zero.

2
On

Another very useful formula for the $k$-th bit of number $b=b_{n}\cdots b_{0}$ is $$b_{k}=\left\lfloor\frac{b}{2^k}\right\rfloor-2\left\lfloor\frac{b}{2^{k+1}}\right\rfloor.$$ This identity can be easily verified by using that, for $b=\sum_{i=0}^{n}b_{i}2^{i}$, we have $\left\lfloor\frac{b}{2^k}\right\rfloor=\sum_{i=k}^{n}b_{i}2^{i-k}$.