How to convert an integer to a string in any base?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Converting an integer to a string in an arbitrary base is a standard algorithm question and a useful utility in real programs. The solution is based on repeated division: each remainder gives one digit, and the digits are collected in reverse order. Once you understand that pattern, bases from 2 through 36 all work the same way.
The Core Algorithm
For a positive integer n and a target base b, repeat these steps until n becomes zero:
- Divide
nbyb. - Record the remainder.
- Replace
nwith the quotient.
Each remainder is a digit in the new base. The first remainder is the least significant digit, so the collected digits must be reversed before returning the final string.
As a quick example, convert decimal 255 to base 16:
- '
255 / 16gives quotient15, remainder15' - '
15 / 16gives quotient0, remainder15'
Remainder 15 maps to F, so the result is FF.
Digit Mapping Matters
Bases larger than 10 need more than the characters 0 through 9. A common mapping is:
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
That supports bases up to 36. If you only need hexadecimal, you can stop at F, but the full alphabet keeps the function general.
Python Implementation
This implementation handles zero, negative numbers, and any base from 2 to 36.
This prints:
The divmod call is convenient because it returns the quotient and remainder together.
Why the Algorithm Works
Each division peels off one digit from the right. In base 10, the last digit of 1234 is what remains after division by 10. The same principle works in any base.
For example, decimal 42 in base 2:
- '
42 / 2remainder0' - '
21 / 2remainder1' - '
10 / 2remainder0' - '
5 / 2remainder1' - '
2 / 2remainder0' - '
1 / 2remainder1'
Reading the remainders from bottom to top gives 101010.
Java Version
If you need the same logic in Java, the code looks very similar.
For very large values, use long or BigInteger instead of int.
Common Pitfalls
- Forgetting to reverse the collected digits before returning the string.
- Not handling zero as a special case, which can produce an empty string.
- Ignoring negative inputs and losing the sign.
- Using a digit table that is too short for the requested base.
- Assuming built-in formatting functions support every arbitrary base you need.
- Overflowing
intwhen the source number is too large.
Summary
- Repeated division plus remainder is the standard base-conversion algorithm.
- The digits are produced from least significant to most significant, so they must be reversed.
- A digit alphabet such as
0-9plusA-Zsupports bases up to36. - Good implementations handle zero, negative numbers, and invalid base values.
- The same algorithm works in Python, Java, and most other languages.

