Convert decimal to a different numerical system

Humans use decimal numbers, computers use binary numbers. A common testing task is to write a function that converts a decimal number to a binary. There is no stl algorithm for that.

But why to stop here, why not to write a function that converts a decimal number to any numerical system with the base from 2-9.

It is actually quite simple.

void dec_to_bin(int dec)
{
  if (dec / 2 != 0)
  {
    dec_to_bin(dec / 2);
  }
  std::cout << dec % 2;
}


It looks like a simple function but there is actually quite a lot going on there. It is a recursive function where all the magic happens when unwinding the stack.

We divide the given decimal number by two (which is our base for decimal). When we reach the point where the decimal number divided by 2 is less than 1, we stop. What happens at that time is, that the stack starts to unwind and the modulus are printed one by one, which at the end gives the binary number. It is interesting to explore it a little bit more about how it works. So I recommend you to put a breakpoint and debug it.

If we another argument to the function, we can simply make the function more general convertor.

void convertor(int dec, int number_system = 2)
{
  if (dec / number_system != 0)
  {
    convertor(dec / number_system, number_system);
  }
  std::cout << dec % number_system;
}

Now we can use this double loop to print numbers from 0 – 128 in the all-numeric system in one shot.

for (int i{}; i < 128; ++i)
{
  for (int j{ 2 }; j < 11; ++j)
  {
    std::cout << i << " - ";
    convertor(i, j);
    std::cout << "\n";
  }
  std::cout << "--------------\n";
}