C++ Notes:Decimal to Binary Conversion

Here is a simple algorithm for converting decimal numbers to binary using repeated division by 2.

Algorithm for converting decimal numbers to binary

The easiest way represent this algorithm is with a table.

nn / 2n % 2
35171
1781
840
420
210
101
  1. Put the number you want to convert in the left column (35 in this example) and put the value of that number divided by 2 (using integer division) in the next column, and the remainder of that division (result of the "mod" operator) in the right column. In the example below, we'll start with the number 35. 35/2 is 17, with remainder 1.
  2. In the next row, copy the middle value (17) into the left, and fill out the other columns appropriately for this number. 17/2 is 8, with remainder 1.
  3. Continue this process until the number in the n/2 column is zero. You could continue, but it will soon be obvious that all further digits from then on will be zeros.
  4. The resulting binary value is in the last column, but must be read from bottom to top. The binary representation of 35 is 100011.

Another Example

Let's convert 6 to binary. Working thru the algorithm with this value gives a binary representation of 110.
nn / 2n % 2
630
311
101