integer conversion
string conversion
base conversion
programming
algorithms

How to convert an integer to a string in any base?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

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:

  1. Divide n by b.
  2. Record the remainder.
  3. Replace n with 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 / 16 gives quotient 15, remainder 15'
  • '15 / 16 gives quotient 0, remainder 15'

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.

python
1DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2
3
4def to_base(n: int, base: int) -> str:
5    if not 2 <= base <= 36:
6        raise ValueError("base must be between 2 and 36")
7
8    if n == 0:
9        return "0"
10
11    negative = n < 0
12    n = abs(n)
13    chars = []
14
15    while n > 0:
16        n, remainder = divmod(n, base)
17        chars.append(DIGITS[remainder])
18
19    if negative:
20        chars.append("-")
21
22    return "".join(reversed(chars))
23
24
25print(to_base(255, 16))
26print(to_base(42, 2))
27print(to_base(-31, 16))

This prints:

text
FF
101010
-1F

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 / 2 remainder 0'
  • '21 / 2 remainder 1'
  • '10 / 2 remainder 0'
  • '5 / 2 remainder 1'
  • '2 / 2 remainder 0'
  • '1 / 2 remainder 1'

Reading the remainders from bottom to top gives 101010.

Java Version

If you need the same logic in Java, the code looks very similar.

java
1public class BaseConverter {
2    private static final String DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
3
4    public static String toBase(int value, int base) {
5        if (base < 2 || base > 36) {
6            throw new IllegalArgumentException("base must be between 2 and 36");
7        }
8        if (value == 0) {
9            return "0";
10        }
11
12        boolean negative = value < 0;
13        int n = Math.abs(value);
14        StringBuilder sb = new StringBuilder();
15
16        while (n > 0) {
17            int remainder = n % base;
18            sb.append(DIGITS.charAt(remainder));
19            n /= base;
20        }
21
22        if (negative) {
23            sb.append('-');
24        }
25
26        return sb.reverse().toString();
27    }
28
29    public static void main(String[] args) {
30        System.out.println(toBase(255, 16));
31    }
32}

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 int when 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-9 plus A-Z supports bases up to 36.
  • Good implementations handle zero, negative numbers, and invalid base values.
  • The same algorithm works in Python, Java, and most other languages.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.