Consider a situation, in which the following function is required:
convert(val1, base1, base2)
It converts a number (val1) from base1 number system to base2 number system. In this function, all arguments are strings, e.g.
convert("34", "012345", "01234567890ABCDEF")
Is called in order to convert 346 -> X16.
When I started thinking of implementation, it came obvious that converting a number with a bigger base to a smaller one requires division operation defined for numbers in the bigger base, e.g. 1210 -> X2 = 12 / 2 | 6 / 2 | 3 / 2 | 1 / 2 | = 11002.
The next though was about doing 2-step-conversion Xb1 -> X10 -> Xb2. This would be definitely easier to implement, but guys, can you please confirm that I’m not wrong in previous conclusion, or is there a clear way to implement such convert() function without an intermediate to-decimal conversion?
Thank you!
Assuming you’re looking for a practical solution in a computer program, you don’t want to convert to base 10 as an intermediate, but instead convert to the computer’s native representation, the base of which is irrelevant. Write two separate functions, one to parse a string into an integer, the other to convert an integer to a string.