How to convert from decimal numbers to binary numbers

From ArticleWorld


Understanding the way computers deal with information is a fundamental skill of a programmer. Being able to work with bases 10 and 2 is very important here, since computers use binary numbers internally, but humans use base 10 for their operations.

How number bases work

The natural base we use is the decimal (base 10) base. We use it because of a simple reason: when people discovered abstract numbers (managing to unbind the number from its physical representation), the most common support they had for counting was their fingers. People had ten fingers. If you take ten fingers ten times, you have 100 fingers. Take these ten more times, and you have 1000 fingers.

Therefore, a the number 188 is represented, in the decimal base, as:

1 * 10^2 + 8 * 10^1 + 8 * 10^0

The same applies for all bases.

How to make the conversion

We will use a "base 2 increment table". This table contains the powers of 2 used for the conversion, starting from the highest. Of course, you need not go to large powers. Start with 1024 (10^10), and keep in mind that you can expand the table to the left by simply multiplying the leftmost term with 2.

1024	512	256	128	64	32	16	8	4	2	1

In our example, we will try to convert the number 356

  1. Look into the table and find the smallest number that will go into 356 no more than one time. In our case, this is 256. Write a 1 and subtract 256 from 356.
  2. Taking the remainder, repeat the procedure above for it. 356 - 256 = 100. In the table, move one position to the right and see if the new number fits into the remainder. In our case, this does not happen. Write a 0, and move one position to the right.
  3. Keep doing this until you get to 1. If the number at the current position in the table does not go into the current remainder, write a 0 and move to the next one. If it does, write a 1, subtract the current number in the table from the current remainder, and move on to the next position with the result of the last subtraction as a remainder.