The Wayback Machine - https://web.archive.org/web/20240603004112/https://www.geeksforgeeks.org/convert-base-decimal-vice-versa/
Open In App

Convert from any base to decimal and vice versa

Last Updated : 26 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number and its base, convert it to decimal. The base of number can be anything such that all digits can be represented using 0 to 9 and A to Z. The value of A is 10, the value of B is 11 and so on. Write a function to convert the number to decimal.

Examples: 

Input number is given as string and output is an integer.

Input: str = "1100", base = 2
Output: 12

Input: str = "11A", base = 16
Output: 282

Input: str = "123", base = 8
Output: 83

We strongly recommend you to minimize your browser and try this yourself first. 
We can always use the below formula to convert from any base to decimal.

"str" is input number as a string 
"base" is the base of the input number.

Decimal Equivalent is,
1*str[len-1] + base*str[len-2] + (base)2*str[len-3] + ...

Below is implementation of above formula.  

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// To return char for a value. For example '2'
// is returned for 2. 'A' is returned for 10. 'B'
// for 11
char reVal(int num)
{
    if (num >= 0 && num <= 9)
        return (char)(num + '0');
    else
        return (char)(num - 10 + 'A');
}
 
// Utility function to reverse a string
void strev(char *str)
{
    int len = strlen(str);
    int i;
    for (i = 0; i < len/2; i++)
    {
        char temp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = temp;
    }
}
 
// Function to convert a given decimal number
// to a base 'base' and
char* fromDeci(char res[], int base, int inputNum)
{
    int index = 0; // Initialize index of result
 
    // Convert input number is given base by repeatedly
    // dividing it by base and taking remainder
    while (inputNum > 0)
    {
        res[index++] = reVal(inputNum % base);
        inputNum /= base;
    }
    res[index] = '\0';
 
    // Reverse the result
    strev(res);
 
    return res;
}
 
// Driver Code
int main()
{
    int inputNum = 282, base = 16;
    char res[100];
    cout << "Decimal Equivalent of " << fromDeci(res, base, inputNum) << " in base "<< base << " is " <<
                                            inputNum;
 
    return 0;
}
 
// This code is contributed by code_hunt.


C




// C program to convert a number from any base
// to decimal
#include <stdio.h>
#include <string.h>
 
// To return value of a char. For example, 2 is
// returned for '2'.  10 is returned for 'A', 11
// for 'B'
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 'b'
// to decimal
int toDeci(char *str, int base)
{
    int len = strlen(str);
    int power = 1; // Initialize power of base
    int num = 0;  // Initialize result
    int i;
 
    // Decimal equivalent is str[len-1]*1 +
    // str[len-2]*base + str[len-3]*(base^2) + ...
    for (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;
        }
 
        num += val(str[i]) * power;
        power = power * base;
    }
 
    return num;
}
 
// Driver code
int main()
{
    char str[] = "11A";
    int base = 16;
    printf("Decimal equivalent of %s in base %d is "
           " %d\n", str, base, toDeci(str, base));
    return 0;
}


Java




// Java program to convert
// a number from any base
// to decimal
import java.io.*;
 
class GFG
{
// To return value of a char.
// For example, 2 is returned
// for '2'. 10 is returned
// for 'A', 11 for 'B'
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
// 'b' to decimal
static int toDeci(String str,
                  int base)
{
    int len = str.length();
    int power = 1; // Initialize
                   // power of base
    int num = 0; // Initialize result
    int i;
 
    // Decimal equivalent is
    // str[len-1]*1 + str[len-2] *
    // base + str[len-3]*(base^2) + ...
    for (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.println("Invalid Number");
        return -1;
        }
 
        num += val(str.charAt(i)) * power;
        power = power * base;
    }
 
    return num;
}
 
// Driver code
public static void main (String[] args)
{
    String str = "11A";
    int base = 16;
    System.out.println("Decimal equivalent of "+
                        str + " in base "+ base +
                                     " is "+ " "+
                              toDeci(str, base));
}
}
 
// This code is contributed
// by anuj_67.


Python3




# Python program to convert a
# number from any base to decimal
 
# To return value of a char.
# For example, 2 is returned
# for '2'. 10 is returned for 'A',
# 11 for 'B'
def val(c):
    if c >= '0' and c <= '9':
        return ord(c) - ord('0')
    else:
        return ord(c) - ord('A') + 10;
 
# Function to convert a number
# from given base 'b' to decimal
def toDeci(str,base):
    llen = len(str)
    power = 1 #Initialize power of base
    num = 0     #Initialize result
 
    # Decimal equivalent is str[len-1]*1 +
    # str[len-2]*base + str[len-3]*(base^2) + ...
    for i in range(llen - 1, -1, -1):
         
        # A digit in input number must
        # be less than number's base
        if val(str[i]) >= base:
            print('Invalid Number')
            return -1
        num += val(str[i]) * power
        power = power * base
    return num
     
# Driver code
strr = "11A"
base = 16
print('Decimal equivalent of', strr,
              'in base', base, 'is',
                 toDeci(strr, base))
 
# This code is contributed
# by Sahil shelangia


C#




// C# program to convert
// a number from any base
// to decimal
using System;
 
class GFG
{
// To return value of a char.
// For example, 2 is returned
// for '2'. 10 is returned
// for 'A', 11 for 'B'
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
// 'b' to decimal
static int toDeci(string str,
                  int b_ase)
{
    int len = str.Length;
    int power = 1; // Initialize
                   // power of base
    int num = 0; // Initialize result
    int i;
 
    // Decimal equivalent is
    // str[len-1]*1 + str[len-2] *
    // base + str[len-3]*(base^2) + ...
    for (i = len - 1; i >= 0; i--)
    {
        // A digit in input number
        // must be less than
        // number's base
        if (val(str[i]) >= b_ase)
        {
        Console.WriteLine("Invalid Number");
        return -1;
        }
 
        num += val(str[i]) * power;
        power = power * b_ase;
    }
 
    return num;
}
 
// Driver code
public static void Main ()
{
    string str = "11A";
    int b_ase = 16;
    Console.WriteLine("Decimal equivalent of "+
                     str + " in base "+ b_ase +
                  " is " + toDeci(str, b_ase));
}
}
 
// This code is contributed
// by anuj_67.


Javascript




<script>
 
// Javascript program to convert
// a number from any base
// to decimal
 
// To return value of a char.
// For example, 2 is returned
// for '2'. 10 is returned
// for 'A', 11 for 'B'
function val(c)
{
    if (c >= '0'.charCodeAt() &&
        c <= '9'.charCodeAt())
        return (c - '0'.charCodeAt());
    else
        return (c - 'A'.charCodeAt() + 10);
}
 
// Function to convert a
// number from given base
// 'b' to decimal
function toDeci(str, b_ase)
{
    let len = str.length;
     
    // Initialize
    // power of base
    let power = 1;
     
    // Initialize result
    let num = 0;
    let i;
 
    // Decimal equivalent is
    // str[len-1]*1 + str[len-2] *
    // base + str[len-3]*(base^2) + ...
    for(i = len - 1; i >= 0; i--)
    {
         
        // A digit in input number
        // must be less than
        // number's base
        if (val(str[i].charCodeAt()) >= b_ase)
        {
            document.write("Invalid Number");
            return -1;
        }
 
        num += val(str[i].charCodeAt()) * power;
        power = power * b_ase;
    }
    return num;
}
 
// Driver code
let str = "11A";
let b_ase = 16;
 
document.write("Decimal equivalent of "+
               str + " in base "+ b_ase +
               " is " + toDeci(str, b_ase));
                
// This code is contributed by divyesh072019
 
</script>


PHP




<?php
// PHP program to convert a number from
// any base to decimal
 
// To return value of a char. For example,
// 2 is returned for '2'. 10 is returned
// for 'A', 11 for 'B'
function val($c)
{
    if ($c >= '0' && $c <= '9')
        return ord($c) - ord('0');
    else
        return ord($c) - ord('A') + 10;
}
 
// Function to convert a number from given
// base 'b' to decimal
function toDeci($str, $base)
{
    $len = strlen($str);
    $power = 1; // Initialize power of base
    $num = 0; // Initialize result
 
    // Decimal equivalent is str[len-1]*1 +
    // str[len-2]*base + str[len-3]*(base^2) + ...
    for ($i = $len - 1; $i >= 0; $i--)
    {
        // A digit in input number must be
        // less than number's base
        if (val($str[$i]) >= $base)
        {
            print("Invalid Number");
            return -1;
        }
 
        $num += val($str[$i]) * $power;
        $power = $power * $base;
    }
 
    return $num;
}
 
// Driver code
$str = "11A";
$base = 16;
print("Decimal equivalent of $str " .
      "in base $base is " . toDeci($str, $base));
 
// This code is contributed by mits
?>


Output

Decimal equivalent of 11A in base 16 is  282

Time Complexity: O(N) n represents the length of string
Auxiliary Space: O(1)

How to do reverse? 

Let the given input decimal number be “inputNum” and target base be “base”. We repeatedly divide inputNum by base and store the remainder. We finally reverse the obtained string. Below is C implementation.

C++




// C++ Program to convert decimal to any given base
#include <bits/stdc++.h>
using namespace std;
 
// To return char for a value. For example '2'
// is returned for 2. 'A' is returned for 10. 'B'
// for 11
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 base 'base' and
string fromDeci(string& res, int base, int inputNum)
{
    int index = 0; // Initialize index of result
 
    // Convert input number is given base by repeatedly
    // dividing it by base and taking remainder
    while (inputNum > 0) {
        res.push_back(reVal(inputNum % base));
        index++;
        inputNum /= base;
    }
 
    // Reverse the result
    reverse(res.begin(), res.end());
 
    return res;
}
 
// Driver program
int main()
{
    int inputNum = 282, base = 16;
    string res;
    cout << "Equivalent of " << inputNum << " in base "
         << base << " is " << fromDeci(res, base, inputNum)
         << endl;
 
    return 0;
}
 
// The code is contributed by Gautam goel (gautamgoel962)


C




// C Program to convert decimal to any given base
#include <stdio.h>
#include <string.h>
 
// To return char for a value. For example '2'
// is returned for 2. 'A' is returned for 10. 'B'
// for 11
char reVal(int num)
{
    if (num >= 0 && num <= 9)
        return (char)(num + '0');
    else
        return (char)(num - 10 + 'A');
}
 
// Utility function to reverse a string
void strev(char *str)
{
    int len = strlen(str);
    int i;
    for (i = 0; i < len/2; i++)
    {
        char temp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = temp;
    }
}
 
// Function to convert a given decimal number
// to a base 'base' and
char* fromDeci(char res[], int base, int inputNum)
{
    int index = 0;  // Initialize index of result
 
    // Convert input number is given base by repeatedly
    // dividing it by base and taking remainder
    while (inputNum > 0)
    {
        res[index++] = reVal(inputNum % base);
        inputNum /= base;
    }
    res[index] = '\0';
 
    // Reverse the result
    strev(res);
 
    return res;
}
 
// Driver program
int main()
{
    int inputNum = 282, base = 16;
    char res[100];
    printf("Equivalent of %d in base %d is "
           " %s\n", inputNum, base, fromDeci(res, base, inputNum));
    return 0;
}


Java




// Java Program to convert decimal to any given base
import java.lang.*;
import java.io.*;
import java.util.*;
 
class GFG
{
     
// To return char for a value. For
// example '2' is returned for 2.
// 'A' is returned for 10. 'B' for 11
static char reVal(int num)
{
    if (num >= 0 && num <= 9)
        return (char)(num + 48);
    else
        return (char)(num - 10 + 65);
}
 
// Function to convert a given decimal number
// to a base 'base' and
static String fromDeci(int base1, int inputNum)
{
    String s = "";
 
    // Convert input number is given
    // base by repeatedly dividing it
    // by base and taking remainder
    while (inputNum > 0)
    {
        s += reVal(inputNum % base1);
        inputNum /= base1;
    }
    StringBuilder ix = new StringBuilder();
 
        // append a string into StringBuilder input1
        ix.append(s);
 
    // Reverse the result
    return new String(ix.reverse());
}
 
// Driver code
public static void main (String[] args)
{
    int inputNum = 282, base1 = 16;
    System.out.println("Equivalent of " + inputNum +
                            " in base "+base1+" is " +
                            fromDeci(base1, inputNum));
}
}
 
// This code is contributed by mits


Python3




# Python3 Program to convert decimal to
# any given base
 
# To return char for a value. For example
# '2' is returned for 2. 'A' is returned
# for 10. 'B' for 11
def reVal(num):
 
    if (num >= 0 and num <= 9):
        return chr(num + ord('0'));
    else:
        return chr(num - 10 + ord('A'));
 
# Utility function to reverse a string
def strev(str):
 
    len = len(str);
    for i in range(int(len / 2)):
        temp = str[i];
        str[i] = str[len - i - 1];
        str[len - i - 1] = temp;
 
# Function to convert a given decimal
# number to a base 'base' and
def fromDeci(res, base, inputNum):
 
    index = 0; # Initialize index of result
 
    # Convert input number is given base
    # by repeatedly dividing it by base
    # and taking remainder
    while (inputNum > 0):
        res+= reVal(inputNum % base);
        inputNum = int(inputNum / base);
 
    # Reverse the result
    res = res[::-1];
 
    return res;
 
# Driver Code
inputNum = 282;
base = 16;
res = "";
print("Equivalent of", inputNum, "in base",
       base, "is", fromDeci(res, base, inputNum));
 
# This code is contributed by mits


C#




// C# Program to convert decimal to any given base
using System;
using System.Collections;
 
class GFG
{
     
// To return char for a value. For
// example '2' is returned for 2.
// 'A' is returned for 10. 'B' for 11
static char reVal(int num)
{
    if (num >= 0 && num <= 9)
        return (char)(num + 48);
    else
        return (char)(num - 10 + 65);
}
 
// Function to convert a given decimal number
// to a base 'base' and
static string fromDeci(int base1, int inputNum)
{
    string s = "";
 
    // Convert input number is given
    // base by repeatedly dividing it
    // by base and taking remainder
    while (inputNum > 0)
    {
        s += reVal(inputNum % base1);
        inputNum /= base1;
    }
    char[] res = s.ToCharArray();
 
    // Reverse the result
    Array.Reverse(res);
    return new String(res);
}
 
// Driver code
static void Main()
{
    int inputNum = 282, base1 = 16;
    Console.WriteLine("Equivalent of " + inputNum +
                            " in base "+base1+" is " +
                            fromDeci(base1, inputNum));
}
}
 
// This code is contributed by mits


Javascript




<script>
    // Javascript Program to convert decimal to any given base
     
    // To return char for a value. For
    // example '2' is returned for 2.
    // 'A' is returned for 10. 'B' for 11
    function reVal(num)
    {
        if (num >= 0 && num <= 9)
            return String.fromCharCode(num + 48);
        else
            return String.fromCharCode(num - 10 + 65);
    }
 
    // Function to convert a given decimal number
    // to a base 'base' and
    function fromDeci(base1, inputNum)
    {
        let s = "";
 
        // Convert input number is given
        // base by repeatedly dividing it
        // by base and taking remainder
        while (inputNum > 0)
        {
            s += reVal(inputNum % base1);
            inputNum = parseInt(inputNum / base1, 10);
        }
        let res = s.split('');
 
        // Reverse the result
        res.reverse();
        return res.join("");
    }
     
    let inputNum = 282, base1 = 16;
    document.write("Equivalent of " + inputNum +
                            " in base "+base1+" is " +
                            fromDeci(base1, inputNum));
 
// This code is contributed by rameshtravel07.
</script>


PHP




<?php
// PHP Program to convert decimal to
// any given base
 
// To return char for a value. For example '2'
// is returned for 2. 'A' is returned for 10.
// 'B' for 11
function reVal($num)
{
    if ($num >= 0 && $num <= 9)
        return chr($num + ord('0'));
    else
        return chr($num - 10 + ord('A'));
}
 
// Utility function to reverse a string
function strev($str)
{
    $len = strlen($str);
    for ($i = 0; $i < $len / 2; $i++)
    {
        $temp = $str[$i];
        $str[$i] = $str[$len - $i - 1];
        $str[$len - $i - 1] = $temp;
    }
}
 
// Function to convert a given decimal
// number to a base 'base' and
function fromDeci($res, $base, $inputNum)
{
    $index = 0; // Initialize index of result
 
    // Convert input number is given base
    // by repeatedly dividing it by base
    // and taking remainder
    while ($inputNum > 0)
    {
        $res.= reVal($inputNum % $base);
        $inputNum = (int)($inputNum / $base);
    }
 
    // Reverse the result
    $res = strrev($res);
 
    return $res;
}
 
// Driver Code
$inputNum = 282;
$base = 16;
$res = "";
print("Equivalent of $inputNum in base $base is " .
                 fromDeci($res, $base, $inputNum));
 
// This code is contributed by mits
?>


Output

Equivalent of 282 in base 16 is 11A

Time Complexity: O(logbasen) where ‘n’ is the input number and ‘base’ is the base to which the number is to be converted. 

Auxiliary Space: O(logbasen)

Method: Using int function

C++




#include <iostream>
#include <string>
 
using namespace std;
 
int main() {
    string n = "1100";
    int b = 2;
    int result = stoi(n, nullptr, b);
    cout << result << endl;
    return 0;
}


Java




public class GFG {
    public static void main(String[] args) {
        String n = "1100";
        int b = 2;
        int result = Integer.parseInt(n, b);
        System.out.println(result);
    }
}


Python3




n = "1100"
b = 2
print(int(n, b))


C#




using System;
 
class Program {
    static void Main(string[] args) {
        string n = "1100";
        int b = 2;
        int result = Convert.ToInt32(n, b);
        Console.WriteLine(result);
    }
}


Javascript




const n = '1100';
const b = 2;
const result = parseInt(n, b);
console.log(result); // Output: 12


Output

12

Time complexity: O(N) Convert input number is given base by repeatedly inputNum dividing it by base and taking remainder takes O(n) complexity 

Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Given a number N in decimal base, find number of its digits in any base (base b)
Given A Number n in a base 10, find the number of digits in its base b representation. Constraints : [Tex]N \in \mathbb{W} [/Tex]Whole Examples : Input : Number = 48 Base = 4 Output: 3 Explanation : (48)10 = (300)4 Input : Number = 1446 Base = 7 Output: 4 Explanation : (446)10 = (4134)7 A simple approach: convert the decimal number into the given b
8 min read
Binary to decimal and vice-versa in python
Write Python code for converting a decimal number to it's binary equivalent and vice-versa. Example: From decimal to binary Input : 8 Output : 1 0 0 0 From binary to decimal Input : 100 Output : 4 Decimal to binary Keep calling conversion function with n/2 till n &gt; 1, later perform n % 1 to get MSB of converted binary number. Example :- 7 1). 7/
4 min read
Given a number N in decimal base, find the sum of digits in any base B
Given a number N in decimal base, the task is to find the sum of digits of the number in any base B. Examples: Input: N = 100, B = 8 Output: 9 Explanation: (100)8 = 144 Sum(144) = 1 + 4 + 4 = 9 Input: N = 50, B = 2 Output: 3 Explanation: (50)2 = 110010 Sum(110010) = 1 + 1 + 0 + 0 + 1 + 0 = 3 Approach: Find unit digit by performing modulo operation
6 min read
Program to Convert Km/hr to miles/hr and vice versa
Given a speed in km/hr, Convert it to m/hr and m/hr to km/hr. Examples: Input : 150 (km/hr) Output : 93.21 Input : 100 (m/hr) Output : 160.92693917 The conversion formula for kph to mph is - 1 kilo-meter = 0.621371192 miles The conversion formula for mph to kph is - 1 miles = 1.60934 kilo-meter C/C++ Code // Cpp program for conversion of // kmph to
4 min read
Program to convert speed in km/hr to m/sec and vice versa
Convert speed given in km/hr to m/sec and vice versa. Examples: Input : kmph = 72, mps = 10 Output : speed_in_mps = 20 speed_in_kmph = 36 Input : kmph = 54, mps = 15 Output : speed_in_mps = 15 speed_in_kmph = 54 Approach: 1 km = 1000 m and 1 hr = 3600 sec (60 min x 60 sec each). Conversion from Km/h to m/sec- When converting km/hr to m/sec, multipl
4 min read
Substrings starting with vowel and ending with consonants and vice versa
Given a string s, count special substrings in it. A Substring of S is said to be special if either of the following properties is satisfied. It starts with a vowel and ends with a consonant.It starts with a consonant and ends with a vowel. Examples: Input : S = "aba" Output : 2 Substrings of S are : a, ab, aba, b, ba, a Out of these only 'ab' and '
17 min read
Minimize changes to make all characters equal by changing vowel to consonant and vice versa
Given a string str[] of lower-case characters, the task is to make all characters of the string equal in the minimum number of operations such that in each operation either choose a vowel and change it to a consonant or vice-versa. Examples: Input: str[] = "geeksforgeeks"Output: 10Explanation: To make all the characters equal, make the following ch
9 min read
Minimize cost to modify the Array such that even indices have even elements and vice versa
Given an array arr[] of size N and two integers X and Y, the task is to find the minimum cost required to modify the array such that even indices have even elements and odd indices have odd elements on them, either by swapping two elements of the array with a cost of X or by incrementing or decrementing 1 from the element with a cost of Y. Examples
7 min read
When to use Array over Linked List and vice versa?
Array: An array is a linear data structure that is a collection of homogeneous elements. Arrays are stored in contiguous memory locations. An array is a static data structure that combines data of similar types. [caption width="800"]Example of an Array[/caption] Linked List: A linked list is a linear data structure that contains nodes and pointers.
2 min read
Count unique Strings by replacing Consonant with closest Vowel and vice versa
Given a string S consisting of lowercase English alphabets, of length N, the task is to find the total number of distinct strings that can be obtained by performing the given operations on every character of the string S: If the character is a consonant, change the character to its closest vowel.If the character is a vowel, change the character to
6 min read
Practice Tags :