{ }codelper
base conversioncharacter codesP0093

From base a to base b

Convert a number written in base a to base b and print it.
Digit values of 10 or more use uppercase English letters: A = 10, B = 11, …, Z = 35.
Neither the input nor the output has unnecessary leading zeros (a value of 0 is the single character 0). The first line gives a and b separated by a space, and the second line gives the number written in base a.

Input
2 ≤ a, b ≤ 36; the number is at least 0 and at most 10¹⁵ in decimal; every digit is 0–9 or A–Z with a value less than a
Output
The number written in base b (uppercase, no leading zeros)
Example 1 · stdin
16 2
FF
stdout
11111111
Example 2 · stdin
10 36
1295
stdout
ZZ
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Reading goes from the front: value = value × a + digit.
Writing produces value % b as the last digit, so each new character goes in front, or you collect them and reverse.
Ready-made tools differ by language: Python int(s, a) reads bases 2–36, but there is no function to write base b (only bin, oct, hex).
Java's Long.parseLong(s, a) and Long.toString(v, b) both take 2–36, and JavaScript/TypeScript have parseInt(s, a) and v.toString(b) — but toString gives lowercase (ff), so toUpperCase() is needed.
C reads with strtoll(s, NULL, a) and C++ with std::stoll(s, nullptr, a); writing is by hand.
In C#, Convert.ToInt64(s, base) and Convert.ToString(v, base) accept only bases 2, 8, 10 and 16 and throw otherwise — so both directions are done by hand.
Craykon keeps DIGITS = "0123…Z", gets a digit value with DIGITS.IndexOf(ch) and a character with DIGITS[v % b]; the quotient is Mathf.Quot(v, b).
Four traps: computing every digit as c - '0' makes 'A' 17 instead of 10 (char subtraction in C, C++, Java, C#).
For 0, while (v > 0) never runs and prints an empty line (the C and C++ solutions use do-while to avoid this).
Appending low digits at the back reverses the order.
And 10¹⁵ exceeds int, so use long/long long (JavaScript and Craykon are exact up to 2^53, so they are fine).

Pythonmain.py · 14 lines
DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" a, b = map(int, input().split())s = input().strip() value = int(s, a)  # int()는 2~36진법 글자를 바로 읽는다(A = 10 … Z = 35)if value == 0:    print("0")else:    out = []    while value > 0:        out.append(DIGITS[value % b])  # 낮은 자리부터 나온다        value //= b    print("".join(reversed(out)))
JavaScriptmain.js · 6 lines
const [line1, s] = require("fs").readFileSync(0, "utf8").trim().split(/\r?\n/);const [a, b] = line1.split(" ").map(Number); // parseInt와 toString은 2~36진법을 받는다. toString은 소문자를 내서 대문자로 바꾼다const value = parseInt(s.trim(), a);console.log(value.toString(b).toUpperCase());
TypeScriptmain.ts · 7 lines
import { readFileSync } from "node:fs";const [line1, s] = readFileSync(0, "utf8").trim().split(/\r?\n/);const [a, b]: number[] = line1.split(" ").map(Number); // parseInt와 toString은 2~36진법을 받는다. toString은 소문자를 내서 대문자로 바꾼다const value: number = parseInt(s.trim(), a);console.log(value.toString(b).toUpperCase());
JavaMain.java · 12 lines
import java.util.Scanner; public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int a = sc.nextInt(), b = sc.nextInt();        String s = sc.next();        // Long.parseLong와 Long.toString은 2~36진법을 받는다. toString은 소문자를 내서 대문자로 바꾼다        long value = Long.parseLong(s, a);        System.out.println(Long.toString(value, b).toUpperCase());    }}
C#Main.cs · 31 lines
using System;using System.Text; class Program{    const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";     static void Main()    {        string[] ab = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        int a = int.Parse(ab[0]), b = int.Parse(ab[1]);        string s = Console.ReadLine().Trim();         // Convert.ToInt64(s, base)는 2·8·10·16진법만 받아서 직접 바꾼다        long value = 0;        foreach (char ch in s) value = value * a + Digits.IndexOf(ch);         if (value == 0)        {            Console.WriteLine("0");            return;        }        var sb = new StringBuilder();        while (value > 0)        {            sb.Insert(0, Digits[(int)(value % b)]); // 낮은 자리부터 나오니 앞에 끼운다            value /= b;        }        Console.WriteLine(sb);    }}
C++main.cpp · 20 lines
#include <algorithm>#include <iostream>#include <string> int main() {    const std::string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";    int a, b;    std::string s;    std::cin >> a >> b >> s;     long long value = std::stoll(s, nullptr, a); // stoll은 2~36진법을 읽는다     std::string out;    do {        out += digits[value % b]; // 낮은 자리부터 나온다. do-while이라 0도 "0"이 된다        value /= b;    } while (value > 0);    std::reverse(out.begin(), out.end());    std::cout << out << '\n';}
Cmain.c · 21 lines
#include <stdio.h>#include <stdlib.h> int main(void) {    const char *digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";    int a, b;    char s[64];    scanf("%d %d %63s", &a, &b, s);     long long value = strtoll(s, NULL, a); /* strtoll은 2~36진법을 읽는다 */     char out[64];    int len = 0;    do {        out[len++] = digits[value % b]; /* 낮은 자리부터 나온다. do-while이라 0도 "0"이 된다 */        value /= b;    } while (value > 0);    for (int i = len - 1; i >= 0; i--) putchar(out[i]);    putchar('\n');    return 0;}
Craykonmain.cray · 28 lines
DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; ab = Console.ReadNumbers();a = ab[0];b = ab[1];s = Console.ReadLine().Trim(); // a진법 글자를 앞에서부터 읽는다: 지금까지의 값 × a + 이 자리 값value = 0;foreach (ch in s){    value = value * a + DIGITS.IndexOf(ch);} if (value == 0){    Console.WriteLine("0");}else{    out = "";    while (value > 0)    {        out = DIGITS[value % b] + out; // 낮은 자리부터 나오니 앞에 붙인다        value = Mathf.Quot(value, b);    }    Console.WriteLine(out);}