Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base 10 to base n conversions [closed]

I'm trying to write a C++ program that does base-conversions.

I want to convert a decimal number to all the other integer bases from 2 to 20.

Is there an efficient and easy-to-implement algorithm for base conversions?

like image 553
Rontogiannis Aristofanis Avatar asked Oct 03 '12 17:10

Rontogiannis Aristofanis


People also ask

Why do we use base 10 instead of base 2?

The base 10 system allows for simple explanations of hundred tens and units etc. Using a base two system such as the Arara tribe in the Amazon would get very repetitive and confusing rather quickly but on the other hand using a base 60 system it would take a long time until you exchange it for another to start again.

How do you convert a decimal to base n?

Decimal to Other Base SystemStep 1 − Divide the decimal number to be converted by the value of the new base. Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 − Divide the quotient of the previous divide by the new base.


2 Answers

I don't understand where exactly is the problem? It's very easy and straigtforward to do base conversion: you do it as you would by hand.

  • divide the number by base
  • write down the remainder
  • repeat the process with the integer part of the division
  • stop when you reach zero
  • the remainders in reverse order give you the digits in base

Example:

1025 (decimal) to base 15:

1025 / 15 = 68 , remainder 5
68   / 15 =  4 , remainder 8
4    / 15 =  0 , remainder 4

The number in base 15 is 485

like image 74
penelope Avatar answered Sep 28 '22 12:09

penelope


You may have two problems:

  • Parsing from the original base to the computer's native integer representation (strtol is quite good at this).

  • Formatting into the new base. (itoa is quite good at this).

If you want to write it yourself, you might like the div function. You feed in the number and the base, and it splits off the rightmost digit. Repeat to get all digits.

If you want to be more efficient, you can divide by the base squared, and get two digits at a time (use a lookup table to get the ASCII characters for both digits). Here's an example of some very efficient implementations. Changing it to use a different base would not be difficult.

like image 43
Ben Voigt Avatar answered Sep 28 '22 14:09

Ben Voigt