#### Archived

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

# Base change algorithm.

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

## 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 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)).

1. 1
2. 2
3. 3
Rutin
23
4. 4
5. 5
khawk
14

• 9
• 11
• 11
• 23
• 10
• ### Forum Statistics

• Total Topics
633651
• Total Posts
3013134
×