Logo

Programming-Idioms

  • C++
  • JS
  • PHP
  • Dart
  • Python

Idiom #308 Integer to string in base b

Create the string representation s of the integer value n in base b.

18 in base 3 -> "200"
26 in base 5 -> "101"
121 in base 12 -> "a1"

from string import digits, ascii_letters
a, s = digits + ascii_letters, ''
while n:
    s = a[n % b] + s
    n = n // b

Value n must be > 0.
import numpy
s = numpy.base_repr(n, b)

Valid range for b is 2-36.
def int_to_base_str(n, b):
    digits = '0123456789abcdefghijklmnopqrstuvwxyz'
    s = ''
    if n == 0: return '0'
    while n:
        n, remainder = divmod(n, b)
        s = digits[remainder] + s
    return s

Works for positive n and for b up to 36.
from string import printable
a, s = printable.rstrip(), ''
while n:
    s = a[n % b] + s
    n = n // b
let s = n.toString(b);
import "strconv"
s := strconv.FormatInt(int64(n), b)

New implementation...
< >
lesmana