Jump to content
  • Advertisement

Archived

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

powdahound

Base change algorithm.

This topic is 5764 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
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)).

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!