Logo

Programming-Idioms

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"

New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#include <string>
using namespace std;
string s;
int x {n}, y, c;
do {
    y = x % b;
    c = y > 9 ? 'a' - 10 : '0';
    s = char(c + y) + s;
} while (x /= b);
import "strconv"
s := strconv.FormatInt(int64(n), b)
let s = n.toString(b);
String s = Integer.toString(n, b);
uses math;
function IntToBaseStr(n: longword; const b: cardinal): string;
const
  digits = '0123456789abcdefghijklmnopqrstuvwxyz';
var
  remainder: longword;
begin
  Result := '';
  repeat
    DivMod(n, b, n, remainder);
    result := digits[remainder + 1] + result;
  until n = 0;
end;
uses fsiconv;
s := IntToStrBase(n,b);
sub int_to_base_str {
    my ($n, $b) = @_;
    my $digits = '0123456789abcdefghijklmnopqrstuvwxyz';
    my ($s, $q, $remainder) = ('');

    return '0' if $n == 0;

    use integer;

    while ($n) {
        ($n, $remainder) = ($n / $b, $n % $b), 
        $s = substr($digits, $remainder, 1) . $s;
    }

    return $s
}
from string import digits, ascii_lowercase
s, d = '', digits + ascii_lowercase
if not n: s = d[n]
else:
    while n:
        s = d[n % b] + s
        n //= b
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
import numpy
s = numpy.base_repr(n, b)
from string import digits, ascii_letters
a, s = digits + ascii_letters, ''
while n:
    s = a[n % b] + s
    n = n // b
s = n.to_s(b)
use radix_fmt::radix;
let s = radix(n, b);