Last Updated : 26 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
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: 12Input: str = "11A", base = 16
Output: 282Input: 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++ 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 11char reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + '0'); else return (char)(num - 10 + 'A');}// Utility function to reverse a stringvoid 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' andchar* 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 Codeint 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 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 decimalint 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 codeint 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 program to convert // a number from any base// to decimalimport 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 decimalstatic 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 codepublic 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.
# 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 codestrr = "11A"base = 16print('Decimal equivalent of', strr, 'in base', base, 'is', toDeci(strr, base))# This code is contributed # by Sahil shelangia
// C# program to convert // a number from any base// to decimalusing 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 decimalstatic 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 codepublic 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.
<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 decimalfunction 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 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 decimalfunction 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++ 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 11char 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' andstring 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 programint 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 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 11char reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + '0'); else return (char)(num - 10 + 'A');}// Utility function to reverse a stringvoid 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' andchar* 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 programint 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 Program to convert decimal to any given baseimport 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 11static 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' andstatic 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 codepublic 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 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 11def 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 stringdef 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' anddef 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 CodeinputNum = 282;base = 16;res = "";print("Equivalent of", inputNum, "in base", base, "is", fromDeci(res, base, inputNum));# This code is contributed by mits
// C# Program to convert decimal to any given baseusing 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 11static 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' andstatic 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 codestatic 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
<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 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 11function reVal($num){ if ($num >= 0 && $num <= 9) return chr($num + ord('0')); else return chr($num - 10 + ord('A'));}// Utility function to reverse a stringfunction 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' andfunction 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
#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;}
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); }}
n = "1100"b = 2print(int(n, b))
using System;class Program { static void Main(string[] args) { string n = "1100"; int b = 2; int result = Convert.ToInt32(n, b); Console.WriteLine(result); }}
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)
Next Article
Decimal to binary conversion without using arithmetic operators
kartik
Improve
Article Tags :
- Mathematical
- DSA
- base-conversion
- Motlay
Practice Tags :
- Motlay
- Mathematical
Similar Reads
- Mathematical Algorithms The following is the list of mathematical coding problem ordered topic wise. Please refer Mathematical Algorithms (Difficulty Wise) for the difficulty wise list of problems. GCD and LCM: GCD of Two Numbers LCM of Two Numbers LCM of array GCD of array Basic and Extended Euclidean Steinâs Algorithm fo 5 min read
- Exponential notation of a decimal number Given a positive decimal number, find the simple exponential notation (x = a·10^b) of the given number. Examples: Input : 100.0 Output : 1E2 Explanation: The exponential notation of 100.0 is 1E2. Input :19 Output :1.9E1 Explanation: The exponential notation of 16 is 1.6E1. Approach: The simplest way 5 min read
- Check if a number is power of k using base changing method This program checks whether a number n can be expressed as power of k and if yes, then to what power should k be raised to make it n. Following example will clarify : Examples: Input : n = 16, k = 2 Output : yes : 4 Explanation : Answer is yes because 16 can be expressed as power of 2. Input : n = 2 8 min read
- Program to convert a binary number to hexadecimal number Given a Binary Number, the task is to convert the given binary number to its equivalent hexadecimal number. The input could be very large and may not fit even into an unsigned long long int.Examples:ÂInput: 110001110Output: 18EInput: 1111001010010100001.010110110011011Output: 794A1.5B36 794A1D9B App 13 min read
- Program for decimal to hexadecimal conversion Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16.Hexadecimal numbers use 16 values to represent a number. Numbers from 0-9 are expressed by digits 0-9 and 8 min read
- Converting a Real Number (between 0 and 1) to Binary String Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print" ERROR:' Examples: Input : (0.625)10 Output : (0.101)2 Input : (0.72)10 Output : ERROR Solution: 12 min read
- Convert from any base to decimal and vice versa 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 a 15+ min read
- Decimal to binary conversion without using arithmetic operators Find the binary equivalent of the given non-negative number n without using arithmetic operators. Examples: Input : n = 10Output : 1010 Input : n = 38Output : 100110 Note that + in below algorithm/program is used for concatenation purpose. Algorithm: decToBin(n) if n == 0 return "0" Declare bin = "" 8 min read