Open in App
Not now

# Convert a number from base A to base B

• Difficulty Level : Medium
• Last Updated : 12 Jan, 2022

Given two positive integers A and B and a string S of size N,  denoting a number in base A, the task is to convert the given string S from base A to base B.

Examples:

Input: S = “10B”, A = 16, B = 10
Output: 267
Explanation: 10B in hexadecimal (base =16) when converted to decimal (base =10) is 267.

Input: S = “10011”, A = 2, B = 8
Output: 23
Explanation: 10011 in binary (base =2) when converted to octal (base = 8) is 23.

Approach: Number systemsis the technique to represent numbers in the computer system architecture. The computer architecture supports the following number systems:

• Binary Number System (Base 2): The binary number system only consists of two digits, 0s and 1s. The base of this number system is 2.
• Octal Number System (Base 8): The octal number system consists of 8 digits ranging from 0 to 7.
• Decimal Number System (Base 10): The decimal number system consists of 10 digits ranging from 0 to 9.
• Hexadecimal Number System (Base 16): The hexadecimal number system consists of 16 digits with 0 to 9 digits and alphabets A to F. It is also known as alphanumeric code as it consists of both number and alphabets.

To convert a number from base A to base B, the idea is to first convert it to its decimal representation and then convert the decimal number to base B

Conversion from any base to Decimal: The decimal equivalent of the number “str” in base “base” is equal to 1 * str[len – 1] + base * str[len – 2] + (base)2 * str[len – 3] + …

Conversion from Decimal to any base:
The decimal number “inputNum” can be converted to a number on base “base” by repeatedly dividing inputNum by base and store the remainder. Finally, reverse the obtained string to get the desired result.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Function to return ASCII` `// value of a character` `int` `val(``char` `c)` `{` `    ``if` `(c >= ``'0'` `&& c <= ``'9'``)` `        ``return` `(``int``)c - ``'0'``;` `    ``else` `        ``return` `(``int``)c - ``'A'` `+ 10;` `}`   `// Function to convert a number` `// from given base to decimal number` `int` `toDeci(string str, ``int` `base)` `{` `    ``// Stores the length` `    ``// of the string` `    ``int` `len = str.size();`   `    ``// Initialize power of base` `    ``int` `power = 1;`   `    ``// Initialize result` `    ``int` `num = 0;`   `    ``// Decimal equivalent is str[len-1]*1` `    ``// + str[len-2]*base + str[len-3]*(base^2) + ...` `    ``for` `(``int` `i = len - 1; i >= 0; i--) {`   `        ``// A digit in input number must` `        ``// be less than number's base` `        ``if` `(val(str[i]) >= base) {` `            ``printf``(``"Invalid Number"``);` `            ``return` `-1;` `        ``}`   `        ``// Update num` `        ``num += val(str[i]) * power;`   `        ``// Update power` `        ``power = power * base;` `    ``}`   `    ``return` `num;` `}`   `// Function to return equivalent` `// character of a given value` `char` `reVal(``int` `num)` `{` `    ``if` `(num >= 0 && num <= 9)` `        ``return` `(``char``)(num + ``'0'``);` `    ``else` `        ``return` `(``char``)(num - 10 + ``'A'``);` `}`   `// Function to convert a given` `// decimal number to a given base` `string fromDeci(``int` `base, ``int` `inputNum)` `{` `    ``// Store the result` `    ``string res = ``""``;`   `    ``// Repeatedly divide inputNum` `    ``// by base and take remainder` `    ``while` `(inputNum > 0) {`   `        ``// Update res` `        ``res += reVal(inputNum % base);`   `        ``// Update inputNum` `        ``inputNum /= base;` `    ``}`   `    ``// Reverse the result` `    ``reverse(res.begin(), res.end());`   `    ``return` `res;` `}`   `// Function to convert a given number` `// from a base to another base` `void` `convertBase(string s, ``int` `a, ``int` `b)` `{` `    ``// Convert the number from` `    ``// base A to decimal` `    ``int` `num = toDeci(s, a);`   `    ``// Convert the number from` `    ``// decimal to base B` `    ``string ans = fromDeci(b, num);`   `    ``// Print the result` `    ``cout << ans;` `}`   `// Driver Code` `int` `main()` `{` `    ``// Given input` `    ``string s = ``"10B"``;` `    ``int` `a = 16, b = 10;`   `    ``// Function Call` `    ``convertBase(s, a, b);`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.util.*;`   `class` `GFG{`   `// Function to return ASCII` `// value of a character` `static` `int` `val(``char` `c)` `{` `    ``if` `(c >= ``'0'` `&& c <= ``'9'``)` `        ``return``(``int``)c - ``'0'``;` `    ``else` `        ``return``(``int``)c - ``'A'` `+ ``10``;` `}`   `// Function to convert a number` `// from given base to decimal number` `static` `int` `toDeci(String str, ``int` `base)` `{` `    `  `    ``// Stores the length` `    ``// of the String` `    ``int` `len = str.length();`   `    ``// Initialize power of base` `    ``int` `power = ``1``;`   `    ``// Initialize result` `    ``int` `num = ``0``;`   `    ``// Decimal equivalent is str[len-1]*1` `    ``// + str[len-2]*base + str[len-3]*(base^2) + ...` `    ``for``(``int` `i = len - ``1``; i >= ``0``; i--)` `    ``{` `        `  `        ``// A digit in input number must` `        ``// be less than number's base` `        ``if` `(val(str.charAt(i)) >= base)` `        ``{` `            ``System.out.printf(``"Invalid Number"``);` `            ``return` `-``1``;` `        ``}`   `        ``// Update num` `        ``num += val(str.charAt(i)) * power;`   `        ``// Update power` `        ``power = power * base;` `    ``}` `    ``return` `num;` `}`   `// Function to return equivalent` `// character of a given value` `static` `char` `reVal(``int` `num)` `{` `    ``if` `(num >= ``0` `&& num <= ``9``)` `        ``return``(``char``)(num + ``'0'``);` `    ``else` `        ``return``(``char``)(num - ``10` `+ ``'A'``);` `}`   `// Function to convert a given` `// decimal number to a given base` `static` `String fromDeci(``int` `base, ``int` `inputNum)` `{` `    `  `    ``// Store the result` `    ``String res = ``""``;`   `    ``// Repeatedly divide inputNum` `    ``// by base and take remainder` `    ``while` `(inputNum > ``0``) ` `    ``{` `        `  `        ``// Update res` `        ``res += reVal(inputNum % base);`   `        ``// Update inputNum` `        ``inputNum /= base;` `    ``}`   `    ``// Reverse the result` `    ``res = reverse(res);`   `    ``return` `res;` `}`   `// Function to convert a given number` `// from a base to another base` `static` `void` `convertBase(String s, ``int` `a, ``int` `b)` `{` `    `  `    ``// Convert the number from` `    ``// base A to decimal` `    ``int` `num = toDeci(s, a);`   `    ``// Convert the number from` `    ``// decimal to base B` `    ``String ans = fromDeci(b, num);`   `    ``// Print the result` `    ``System.out.print(ans);` `}`   `static` `String reverse(String input)` `{` `    ``char``[] a = input.toCharArray();` `    ``int` `l, r = a.length - ``1``;` `    ``for``(l = ``0``; l < r; l++, r--) ` `    ``{` `        ``char` `temp = a[l];` `        ``a[l] = a[r];` `        ``a[r] = temp;` `    ``}` `    ``return` `String.valueOf(a);` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `    `  `    ``// Given input` `    ``String s = ``"10B"``;` `    ``int` `a = ``16``, b = ``10``;`   `    ``// Function Call` `    ``convertBase(s, a, b);` `}` `}`   `// This code is contributed by 29AjayKumar`

## Python3

 `# Python program for the above approach`   `# Function to return ASCII` `# value of a character` `def` `val(c):` `    ``if` `(c >``=` `'0'` `and` `c <``=` `'9'``):` `        ``return` `ord``(c) ``-` `48` `    ``else``:` `        ``return` `ord``(c) ``-` `65`  `+` `10`   `# Function to convert a number` `# from given base to decimal number` `def` `toDeci(strr, base):` `    `  `    ``# Stores the length` `    ``# of the string` `    ``lenn ``=` `len``(strr)` `    `  `    ``# Initialize power of base` `    ``power ``=` `1` `    `  `    ``# Initialize result` `    ``num ``=` `0` `    `  `    ``# Decimal equivalent is strr[len-1]*1` `    ``# + strr[len-2]*base + strr[len-3]*(base^2) + ...` `    ``for` `i ``in` `range``(lenn ``-` `1``, ``-``1``, ``-``1``):` `        ``# A digit in input number must` `        ``# be less than number's base` `        ``if` `(val(strr[i]) >``=` `base):` `            ``print``(``"Invalid Number"``)` `            ``return` `-``1` `            `  `        ``# Update num` `        ``num ``+``=` `val(strr[i]) ``*` `power` `        `  `        ``# Update power` `        ``power ``=` `power ``*` `base` `    `  `    ``return` `num`   `# Function to return equivalent` `# character of a given value` `def` `reVal(num):` `    `  `    ``if` `(num >``=` `0` `and` `num <``=` `9``):` `        ``return` `chr``(num ``+` `48``)` `    ``else``:` `        ``return` `chr``(num ``-` `10` `+` `65``)`     `# Function to convert a given` `# decimal number to a given base` `def` `fromDeci(base, inputNum):` `    `  `    ``# Store the result` `    ``res ``=` `""` `    `  `    ``# Repeatedly divide inputNum` `    ``# by base and take remainder` `    ``while` `(inputNum > ``0``):` `        `  `        ``# Update res` `        ``res ``+``=` `reVal(inputNum ``%` `base)` `        `  `        ``# Update inputNum` `        ``inputNum ``/``/``=` `base` `        `  `    ``# Reverse the result` `    ``res ``=` `res[::``-``1``]` `    `  `    ``return` `res`     `# Function to convert a given number` `# from a base to another base` `def` `convertBase(s, a, b):` `    `  `    ``# Convert the number from` `    ``# base A to decimal` `    ``num ``=` `toDeci(s, a)`   `    ``# Convert the number from` `    ``# decimal to base B` `    ``ans ``=` `fromDeci(b, num)`   `    ``# Print the result` `    ``print``(ans)`     `# Driver Code`   `# Given input` `s ``=` `"10B"` `a ``=` `16` `b ``=` `10`   `# Function Call` `convertBase(s, a, b)`   `# This code is contributed by shubhamsingh10`

## C#

 `// C# program for the above approach` `using` `System;`   `public` `class` `GFG{` `    `  `    ``// Function to return ASCII` `    ``// value of a character` `    ``static` `int` `val(``char` `c)` `    ``{` `        ``if` `(c >= ``'0'` `&& c <= ``'9'``)` `            ``return``(``int``)c - ``'0'``;` `        ``else` `            ``return``(``int``)c - ``'A'` `+ 10;` `    ``}` `    `  `    ``// Function to convert a number` `    ``// from given basse to decimal number` `    ``static` `int` `toDeci(``string` `str, ``int` `basse)` `    ``{` `        `  `        ``// Stores the length` `        ``// of the string` `        ``int` `len = str.Length;` `    `  `        ``// Initialize power of basse` `        ``int` `power = 1;` `    `  `        ``// Initialize result` `        ``int` `num = 0;` `    `  `        ``// Decimal equivalent is str[len-1]*1` `        ``// + str[len-2]*basse + str[len-3]*(basse^2) + ...` `        ``for``(``int` `i = len - 1; i >= 0; i--)` `        ``{` `            `  `            ``// A digit in input number must` `            ``// be less than number's basse` `            ``if` `(val(str[i]) >= basse)` `            ``{` `                ``Console.Write(``"Invalid Number"``);` `                ``return` `-1;` `            ``}` `    `  `            ``// Update num` `            ``num += val(str[i]) * power;` `    `  `            ``// Update power` `            ``power = power * basse;` `        ``}` `        ``return` `num;` `    ``}` `    `  `    ``// Function to return equivalent` `    ``// character of a given value` `    ``static` `char` `reVal(``int` `num)` `    ``{` `        ``if` `(num >= 0 && num <= 9)` `            ``return``(``char``)(num + ``'0'``);` `        ``else` `            ``return``(``char``)(num - 10 + ``'A'``);` `    ``}` `    `  `    ``// Function to convert a given` `    ``// decimal number to a given basse` `    ``static` `string` `fromDeci(``int` `basse, ``int` `inputNum)` `    ``{` `        `  `        ``// Store the result` `        ``string` `res = ``""``;` `    `  `        ``// Repeatedly divide inputNum` `        ``// by basse and take remainder` `        ``while` `(inputNum > 0) ` `        ``{` `            `  `            ``// Update res` `            ``res += reVal(inputNum % basse);` `    `  `            ``// Update inputNum` `            ``inputNum /= basse;` `        ``}` `    `  `        ``// Reverse the result` `        ``res = reverse(res);` `    `  `        ``return` `res;` `    ``}` `    `  `    ``// Function to convert a given number` `    ``// from a basse to another basse` `    ``static` `void` `convertbasse(``string` `s, ``int` `a, ``int` `b)` `    ``{` `        `  `        ``// Convert the number from` `        ``// basse A to decimal` `        ``int` `num = toDeci(s, a);` `    `  `        ``// Convert the number from` `        ``// decimal to basse B` `        ``string` `ans = fromDeci(b, num);` `    `  `        ``// Print the result` `        ``Console.Write(ans);` `    ``}` `    `  `    ``static` `string` `reverse(``string` `input)` `    ``{` `        ``char``[] a = input.ToCharArray();` `        ``int` `l, r = a.Length - 1;` `        ``for``(l = 0; l < r; l++, r--) ` `        ``{` `            ``char` `temp = a[l];` `            ``a[l] = a[r];` `            ``a[r] = temp;` `        ``}` `        ``return` `new` `string``(a);` `    ``}` `    `  `    ``// Driver Code` `    ``static` `public` `void` `Main (){` `        ``// Given input` `        ``string` `s = ``"10B"``;` `        ``int` `a = 16, b = 10;` `    `  `        ``// Function Call` `        ``convertbasse(s, a, b);` `    ``}` `}`   `// This code is contributed by shubhamsingh10`

## Javascript

 ``

Output:

`267`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles