Archived

This topic is now archived and is closed to further replies.

Base change algorithm.

This topic is 5513 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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)).

Share this post


Link to post
Share on other sites