what is the general formula to convert a base 10 number to a base 2 number?

90 Views Asked by At

I have this question where I need to convert to base 2. what is the general formula that takes a natural number and converts it into its base 2 number?

2

There are 2 best solutions below

0
On

There are several different algorithms. One general method of converting to base b is to repeatedly divide by b, and the remainders constitute the digits in reverse order. For example, 52 in base 2:

26 remainder 0
13 remainder 0
6 remainder 1
3 remainder 0
1 remainder 1
0 remainder 1

So 52base 10 = 110100base 2

0
On

This should be basic.

$n = \sum_{i = 1}^k a_i 2^i$ where each $a_i = \{0,1\}$. Your job is to figure out two things. 1) What is $k$? 2) what are all the $a_i$s?

1) Figure out the largest integer where $2^k \le n < 2^{k+1}$. That is $k$.

2) And $a_k$ will always be $1$. To find out the rest of the $a_i$s. Subtract $2^{k}$ from $n$ to get $n_k = \sum_{i=0}^{k-1} a_i 2^i = n - a_k \cdot 2^k$.

To find out what $a_{k-1}$ is, check if $n_k \ge 2^{k-1}$. If so $a_{k-1} = 1$. If $n_k < 2^{k-1}$ then $a_{k-1} = 0$.

Just repeat step 2) to get all the $a_i$.

Example if $n = 1000$ then

$512 = 2^9 < n < 2^{10} =1024$

So $k= 9$ and $a_9=1$. $1000 - 512 = 488$ and $n = 2^9 \cdot 1 + 488$.

$2^8=256 < 488 < 512=2^9$ so $a_8 = 1$. $488-256=232$ and $n = 2^9 \cdot 1 + 2^8 \cdot 1$.

$2^7=128 < 232 < 2^8 = 512$ so $a^7 = 1$. $256-232 = 24$ and $n = 2^9 \cdot 1 +2^8 \cdot 1 + 2^7 \cdot 1$.

$2^6=64 > 24$ so $a^6 = 0$. and $n = 2^9 \cdot 1 + 2^8 \cdot 1 + 2^7 \cdot 1 + 2^6 \cdot 0$.

$2^5 = 32 > 24$ so $a^5 =0$. and $n = 2^9 \cdot 1 + 2^8 \cdot 1 + 2^7 \cdot 1 + 2^6 \cdot 0+2^5 \cdot 0$.

$2^4 = 16 < 24 < 2^5 = 32$ so $a^4 = 1$. $24-16 = 8$. and $n=2^9 \cdot 1 + 2^8 \cdot 1 + 2^7 \cdot 1 + 2^6 \cdot 0 + 2^5 \cdot 0 + 2^4 \cdot 1$.

$2^3 = 8 \le 8 < 2^4$ so $a^3 = 1$. $8-8=0$. and $n=2^9 \cdot 1 + 2^8 \cdot 1 + 2^7 \cdot 1 + 2^6 \cdot 0 + 2^5 \cdot 0 + 2^4 \cdot 1+ 2^3 \cdot 1$.

We've reached $0$ so we are done. The reast will all be $0$s. $n=2^9 \cdot 1 + 2^8 \cdot 1 + 2^7 \cdot 1 + 2^6 \cdot 0 + 2^5 \cdot 0 + 2^4 \cdot 1+ 2^3 \cdot 1+2^2 \cdot 0 + 2^1 \cdot 0 +2^0 \cdot 0 = 1110011000_2$