Base change algorithm.

Started by
0 comments, last by powdahound 21 years, 5 months ago
I''m trying to write a function that will take a number and a new base and convert the number to that new base. If I do base will I have to check for and replace some of the numbers with letters and all that or is there an easier way to do this? Thanks. powdahound''s lodge
Advertisement
quote:Original post by powdahound
I''m trying to write a function that will take a number and a new base and convert the number to that new base. If I do base will I have to check for and replace some of the numbers with letters and all that or is there an easier way to do this? Thanks.

powdahound''s lodge


Assuming the input number is always in decimal base because of its natural semantics (using variable input base complicates things slightly):
result = 0;place = 1;while( number ){  result += (number % base) * place;  number /= base;  place *= 10;  // to simulate appropriate digit place} 

Pitfalls include the fact that some bases require more digits to represent an equivalent value than others. To eliminate this consideration, you''ll probably want your result to be some sort of string (which changes the exact operations slightly, but not the algorithm).

For bases >10 you''ll need to test whether the value of (number % base) is greater than base, in which case you''ll need to replace its decimal value with the alphabetical equivalent (which can be obtained as ''a'' + ((number % base) -10)).

This topic is closed to new replies.

Advertisement