Program for Binary To Decimal Conversion
Last Updated :
01 Mar, 2024
Given a binary number as input, we need to write a program to convert the given binary number into an equivalent decimal number.
Check:
Binary to Decimal Converter
Examples :
Input : 111
Output : 7
Input : 1010
Output : 10
Input: 100001
Output: 33
The idea is to extract the digits of a given binary number starting from the rightmost digit and keep a variable dec_value. At the time of extracting digits from the binary number, multiply the digit with the proper base (Power of 2) and add it to the variable dec_value. In the end, the variable dec_value will store the required decimal number.
For Example:
If the binary number is 111.
dec_value = 1*(2^2) + 1*(2^1) + 1*(2^0) = 7
The below diagram explains how to convert ( 1010 ) to equivalent decimal value:

Below is the implementation of the above idea :
C++
#include <iostream>
using namespace std;
int binaryToDecimal(int n)
{
int num = n;
int dec_value = 0;
int base = 1;
int temp = num;
while (temp) {
int last_digit = temp % 10;
temp = temp / 10;
dec_value += last_digit * base;
base = base * 2;
}
return dec_value;
}
int main()
{
int num = 10101001;
cout << binaryToDecimal(num) << endl;
}
|
Java
class GFG {
static int binaryToDecimal(int n)
{
int num = n;
int dec_value = 0;
int base = 1;
int temp = num;
while (temp > 0) {
int last_digit = temp % 10;
temp = temp / 10;
dec_value += last_digit * base;
base = base * 2;
}
return dec_value;
}
public static void main(String[] args)
{
int num = 10101001;
System.out.println(binaryToDecimal(num));
}
}
|
C#
class GFG {
public static int binaryToDecimal(int n)
{
int num = n;
int dec_value = 0;
int base1 = 1;
int temp = num;
while (temp > 0) {
int last_digit = temp % 10;
temp = temp / 10;
dec_value += last_digit * base1;
base1 = base1 * 2;
}
return dec_value;
}
public static void Main()
{
int num = 10101001;
System.Console.Write(binaryToDecimal(num));
}
}
|
Javascript
<script>
function binaryToDecimal(n)
{
let num = n;
let dec_value = 0;
let base = 1;
let temp = num;
while (temp) {
let last_digit = temp % 10;
temp = Math.floor(temp / 10);
dec_value += last_digit * base;
base = base * 2;
}
return dec_value;
}
let num = 10101001;
document.write(binaryToDecimal(num) + "<br>");
</script>
|
PHP
<?php
function binaryToDecimal($n)
{
$num = $n;
$dec_value = 0;
$base = 1;
$temp = $num;
while ($temp)
{
$last_digit = $temp % 10;
$temp = $temp / 10;
$dec_value += $last_digit
* $base;
$base = $base*2;
}
return $dec_value;
}
$num = 10101001;
echo binaryToDecimal($num), "\n";
?>
|
Python3
def binaryToDecimal(n):
num = n;
dec_value = 0;
base = 1;
temp = num;
while(temp):
last_digit = temp % 10;
temp = int(temp / 10);
dec_value += last_digit * base;
base = base * 2;
return dec_value;
num = 10101001;
print(binaryToDecimal(num));
|
Time complexity : O( log n) We can also say time complexity as O(d) where d is number of digits.
Auxiliary Space : O(1)
Note: The program works only with binary numbers in the range of integers. In case you want to work with long binary numbers like 20 bits or 30 bit, you can use a string variable to store the binary numbers.
Below is a similar program which uses string variable instead of integers to store binary value:
C++
#include <iostream>
#include <string>
using namespace std;
int binaryToDecimal(string n)
{
string num = n;
int dec_value = 0;
int base = 1;
int len = num.length();
for (int i = len - 1; i >= 0; i--) {
if (num[i] == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
int main()
{
string num = "10101001";
cout << binaryToDecimal(num) << endl;
}
|
Java
import java.io.*;
class GFG {
static int binaryToDecimal(String n)
{
String num = n;
int dec_value = 0;
int base = 1;
int len = num.length();
for (int i = len - 1; i >= 0; i--) {
if (num.charAt(i) == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
public static void main(String[] args)
{
String num = new String("10101001");
System.out.println(binaryToDecimal(num));
}
}
|
C#
using System;
class GFG {
static int binaryToDecimal(String n)
{
String num = n;
int dec_value = 0;
int base1 = 1;
int len = num.Length;
for (int i = len - 1; i >= 0; i--) {
if (num[i] == '1')
dec_value += base1;
base1 = base1 * 2;
}
return dec_value;
}
public static void Main()
{
String num = "10101001";
Console.WriteLine(binaryToDecimal(num));
}
}
|
Javascript
<script>
function binaryToDecimal(n)
{
let num = n;
let dec_value = 0;
let base = 1;
let len = num.length;
for (let i = len - 1; i >= 0; i--) {
if (num[i] == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
let num = "10101001";
document.write(binaryToDecimal(num) + "<br>");
</script>
|
PHP
<?php
function binaryToDecimal($n)
{
$num = $n;
$dec_value = 0;
$base = 1;
$len = strlen($num);
for ($i = $len - 1; $i >= 0; $i--)
{
if ($num[$i] == '1')
$dec_value += $base;
$base = $base * 2;
}
return $dec_value;
}
$num = "10101001";
echo binaryToDecimal($num), "\n";
?>
|
Python3
def binaryToDecimal(n):
num = n;
dec_value = 0;
base1 = 1;
len1 = len(num);
for i in range(len1 - 1, -1, -1):
if (num[i] == '1'):
dec_value += base1;
base1 = base1 * 2;
return dec_value;
num = "10101001";
print(binaryToDecimal(num));
|
Time complexity : O(n) where n is the length of the string.
Auxiliary Space : O(1)
Here is another way to convert decimal to binary numbers which is more intuitive and faster. At every iteration we extract the last digit (or a character in case of string input), check if it is a 1, if it is then multiply by the power of 2(where the power depends on which bit we are currently on ) and add it to the decimal number( initially = 0 ) .If it is a 0, then we don’t need to add anything to our decimal value since that bit is not contributing, so just increase the power and move to the next bit.
If we left shift 1 by n times ( 1<<n ), we basically get 2^n. Hence we use left shift operator( << ) to find the powers of two since it is faster.
1) If the input is of int type :
C++
#include <iostream>
using namespace std;
int binaryToDecimal(int n)
{
int dec_num = 0 ;
int power = 0 ;
while(n>0){
if(n%10 == 1){
dec_num += (1<<power) ;
}
power++ ;
n = n / 10 ;
}
return dec_num ;
}
int main()
{
int num = 10101001;
cout << binaryToDecimal(num) << endl;
}
|
Java
public class BinaryToDecimal {
public static int binaryToDecimal(int n)
{
int dec_num = 0;
int power = 0;
while (n > 0) {
if (n % 10 == 1) {
dec_num += (1 << power);
}
power++;
n = n / 10;
}
return dec_num;
}
public static void main(String[] args)
{
int num = 10101001;
System.out.println(binaryToDecimal(num));
}
}
|
C#
using System;
public class Program
{
public static int BinaryToDecimal(int n)
{
int dec_num = 0;
int power = 0;
while (n > 0)
{
if (n % 10 == 1)
{
dec_num += (1 << power);
}
power++;
n = n / 10;
}
return dec_num;
}
public static void Main()
{
int num = 10101001;
Console.WriteLine(BinaryToDecimal(num));
}
}
|
Javascript
function binaryToDecimal(n) {
let dec_num = 0;
let power = 0;
while (n > 0) {
if (n % 10 === 1) {
dec_num += (1 << power);
}
power++;
n = Math.floor(n / 10);
}
return dec_num;
}
let num = 10101001;
console.log(binaryToDecimal(num));
|
Python3
import math
def binaryToDecimal(n):
dec_num = 0
power = 0
while (n > 0):
if (n % 10 == 1):
dec_num += (1 << power)
power = power + 1
n = math.floor(n / 10)
return dec_num
num = 10101001
print(binaryToDecimal(num))
|
Time complexity : O(log n)
Space complexity : O(1)
2) If the input is of string type :
C++
#include <iostream>
#include <string>
using namespace std;
int binaryToDecimal(string str)
{
int dec_num = 0;
int power = 0 ;
int n = str.length() ;
for(int i = n-1 ; i>=0 ; i--){
if(str[i] == '1'){
dec_num += (1<<power) ;
}
power++ ;
}
return dec_num;
}
int main()
{
string num = "10101001";
cout << binaryToDecimal(num) << endl;
}
|
Java
import java.util.*;
public class BinaryToDecimal {
public static int binaryToDecimal(String str) {
int dec_num = 0;
int power = 0;
int n = str.length();
for (int i = n - 1; i >= 0; i--) {
if (str.charAt(i) == '1') {
dec_num += (int) Math.pow(2, power);
}
power++;
}
return dec_num;
}
public static void main(String[] args) {
String num = "10101001";
System.out.println(binaryToDecimal(num));
}
}
|
C#
using System;
class Program {
static int binaryToDecimal(string str)
{
int dec_num = 0;
int power = 0;
int n = str.Length;
for (int i = n - 1; i >= 0; i--) {
if (str[i] == '1') {
dec_num += (1 << power);
}
power++;
}
return dec_num;
}
static void Main(string[] args)
{
string num = "10101001";
Console.WriteLine(binaryToDecimal(num));
}
}
|
Javascript
function binaryToDecimal(str)
{
let dec_num = 0;
let power = 0 ;
let n = str.length;
for(let i = n-1 ; i>=0 ; i--){
if(str[i] == '1'){
dec_num += (1<<power) ;
}
power++ ;
}
return dec_num;
}
let num = "10101001";
console.log(binaryToDecimal(num));
|
Python3
def binaryToDecimal(str):
dec_num = 0
power = 0
n = len(str)
for i in range(n - 1, -1, -1):
if (str[i] == '1'):
dec_num += (2 ** power)
power += 1
return dec_num
num = "10101001"
print(binaryToDecimal(num))
|
Time complexity: O(k) [since at max, we will have to process 32 bits which will take 32 iterations.]
Auxiliary Space : O(1)
Using pre-defined function:
C++
#include <iostream>
using namespace std;
int main()
{
char binaryNumber[] = "1001";
cout << stoi(binaryNumber, 0, 2);
return 0;
}
|
C
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
char binaryNumber[] = "1001";
int bin, dec = 0;
bin = atoi(binaryNumber);
for(int i = 0; bin; i++, bin /= 10)
if (bin % 10)
dec += pow(2, i);
printf("%d", dec);
return 0;
}
|
Java
public class GFG {
public static void main(String args[])
{
String binaryNumber = "1001";
System.out.println(Integer.parseInt(binaryNumber, 2));
}
}
|
C#
using System;
class GFG {
public static void Main()
{
int value = 1001;
Console.Write(Convert.ToInt32(value.ToString(), 2));
}
}
|
Javascript
<script>
var binaryNumber = "1001";
document.write(parseInt(binaryNumber, 2));
</script>
|
Python3
n = input()
s = int(n, 2)
print(s)
|
Time complexity: O(n) where n is the length of the given string.
Auxiliary Space: O(1)
3) Using Horner’s scheme
Horner’s scheme is an efficient approach for computing polynomials and it can be redirected into different other scenarios like converting numbers from one numerical system to another (Binary to decimal, etc.), evaluating the Taylor series, etc.
Given a polynomial of degree n, Cnxn + Cn-1xn-1 + Cn-2 xn-2 +…+C1x + C0, it can be nested such that the solution is achieved with n multiplications and n additions using this scheme. Simply put, starting from the first coefficient, multiply by x and add the next coefficient.
Cnxn + Cn-1xn-1 + Cn-2 xn-2 +…+C1x + C0 = (((Cnx + Cn-1)x + Cn-2)x + Cn-3)x +… + C0
Example:
3x3 + 4x2 + 6x + 3 = ((3x + 4)x + 6)x + 3
Observe that when we expand a binary number, it takes the form of a polynomial:
Polynomial: Cnxn + Cn-1xn-1 + Cn-2xn-2 +…+C1x + C0
Binary expansion: digitn(2n) + digitn-1(2n-1) + digitn-2(2n-2) + … + digit0(20)
The constants in the polynomial form are replaced by digits of the binary number and x=2. Hence, we can just use the same polynomial trick on this conversion:
Example:
101002
= 1*24 + 0*23 + 1*22 + 0*21 + 0*20
= (((1(2) + 0)2 + 1)2 + 0)2 + 0
= 20
C++
#include <iostream>
#include <string>
int main() {
std::string binaryNumber;
std::cout << "Enter Binary number: ";
std::getline(std::cin, binaryNumber);
int decimalNumber = 0;
for (size_t i = 0; i < binaryNumber.length(); i++) {
decimalNumber = decimalNumber * 2 + (binaryNumber[i] - '0');
}
std::cout << "Decimal: " << decimalNumber << std::endl;
return 0;
}
|
Java
import java.util.Scanner;
public class BinaryToDecimal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Binary number: ");
String binaryNumber = scanner.nextLine();
int decimalNumber = 1;
for (int i = 0; i < binaryNumber.length() - 1; i++) {
decimalNumber = decimalNumber * 2 + Character.getNumericValue(binaryNumber.charAt(i + 1));
}
System.out.print("Decimal: ");
System.out.println(decimalNumber);
scanner.close();
}
}
|
C#
using System;
class Program {
static void Main(string[] args)
{
string binaryNumber;
Console.Write("Enter Binary number: ");
binaryNumber = Console.ReadLine();
if (string.IsNullOrEmpty(binaryNumber)) {
Console.WriteLine("Decimal: 0");
return;
}
int decimalNumber = 0;
for (int i = 0; i < binaryNumber.Length; i++) {
decimalNumber = decimalNumber * 2
+ (binaryNumber[i] - '0');
}
Console.WriteLine("Decimal: " + decimalNumber);
}
}
|
Javascript
var n = prompt("Enter Binary number: ");
var dec = 1;
for (var i = 0; i < n.length - 1; i++) {
dec = dec * 2 + parseInt(n[i + 1]);
}
console.log("Decimal: " + dec);
|
Python3
n = input("Enter Binary number: ")
dec = 1
for i in range(len(n)-1):
dec = dec*2 + int(n[i+1])
print("Decimal: ", end = "")
print(dec)
|
Output:
Enter Binary number: 10010
Decimal: 18
Time complexity: O(n)
Decreased operations: Horners scheme only takes n multiplications and n additions for the conversion.
Similar Reads
Ring Counter in Digital Logic
A ring counter is a typical application of the Shift register. The ring counter is almost the same as the shift counter. The only change is that the output of the last flip-flop is connected to the input of the first flip-flop in the case of the ring counter but in the case of the shift register it
3 min read
n-bit Johnson Counter in Digital Logic
Prerequisite - Counters Johnson counter also known as creeping counter, is an example of synchronous counter. In Johnson counter, the complemented output of last flip flop is connected to input of first flip flop and to implement n-bit Johnson counter we require n flip-flop. It is one of the most i
5 min read
Ripple Counter in Digital Logic
Counters play a crucial role in digital logic circuits, enabling tasks such as clock frequency division and sequencing. This article explores the concept of ripple counters, a type of asynchronous counter, their operation, advantages, and disadvantages in digital logic design. What is a Counter?Coun
5 min read
Design counter for given sequence
A Counter is a device which stores (and sometimes displays) the number of times a particular event or process has occurred, often in relationship to a clock signal. Counters are used in digital electronics for counting purpose, they can count specific event happening in the circuit. For example, in
3 min read
Master-Slave JK Flip Flop
Prerequisite -Flip-flop types and their ConversionRace Around Condition In JK Flip-flop - For J-K flip-flop, if J=K=1, and if clk=1 for a long period of time, then Q output will toggle as long as CLK is high, which makes the output of the flip-flop unstable or uncertain. This problem is called race
4 min read
Asynchronous Sequential Circuits
An asynchronous sequential circuit does not have the clock signal; the transitions between different states occur due to the ‘change of inputs’. This makes them suitable for applications which involve low power input or when a clock signal may not be needed. In this article, we explain how these cir
7 min read
Shift Registers in Digital Logic
Pre-Requisite: Flip-Flops Flip flops can be used to store a single bit of binary data (1 or 0). However, in order to store multiple bits of data, we need multiple flip-flops. N flip flops are to be connected in order to store n bits of data. A Register is a device that is used to store such informat
8 min read
Design 101 sequence detector (Mealy machine)
A sequence detector is a sequential state machine that takes an input string of bits and generates an output 1 whenever the target sequence has been detected. In a Mealy machine, output depends on the present state and the external input (x). Hence, in the diagram, the output is written outside the
5 min read
Amortized analysis for increment in counter
Amortized analysis refers to determining the time-averaged running time for a sequence (not an individual) operation. It is different from average case analysis because here, we don't assume that the data arranged in average (not very bad) fashion like we do for average case analysis for quick sort.
4 min read
Number System and Base Conversions
Electronic and Digital systems may use a variety of different number systems, (e.g. Decimal, Hexadecimal, Octal, Binary), or even Duodecimal or less well known but better named Uncial. All the other bases other than Decimal result from computer usage. Uncial (named from Latin for 1/12 "uncia" the ba
5 min read
Code Converters - BCD(8421) to/from Excess-3
Prerequisite - Number System and base conversions Excess-3 binary code is an unweighted self-complementary BCD code. Self-Complementary property means that the 1's complement of an excess-3 number is the excess-3 code of the 9's complement of the corresponding decimal number. This property is useful
5 min read
Code Converters - Binary to/from Gray Code
In this article, we will go through Code Converters - Binary to/from Gray Code,we will start our article by defining Code converters, Binary code and Gray code, and then we will go through the conversion of binary code to gray code and vice versa. At last, we will conclude our article with some faqs
9 min read
Program for Decimal to Binary Conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number. Examples of Decimal to Binary: Input : 7Output : 111Input : 10Output : 1010Input: 33Output: 100001Recommended PracticeDecimal to binaryTry It!Brute force ApproachFor Exa
15+ min read
Program for Binary To Decimal Conversion
Given a binary number as input, we need to write a program to convert the given binary number into an equivalent decimal number. Check: Binary to Decimal ConverterExamples : Input : 111Output : 7Input : 1010Output : 10Input: 100001Output: 33Recommended PracticeBinary number to decimal numberTry It!
15+ min read
Program for Decimal to Octal Conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent octal number. i.e convert the number with base value 10 to base value 8. The base value of a number system determines the number of digits used to represent a numeric value. For example
10 min read
Program for Octal to Decimal Conversion
Given an octal number as input, we need to write a program to convert the given octal number into equivalent decimal number. Examples: Input : 67Output: 55Input : 512Output: 330Input : 123Output: 83The idea is to extract the digits of a given octal number starting from the rightmost digit and keep a
11 min read
Program for Hexadecimal to Decimal
Given a hexadecimal number as input, we need to write a program to convert the given hexadecimal number into an equivalent decimal number. Examples: Input : 67Output: 103Input : 512Output: 1298Input : 123Output: 291We know that hexadecimal number uses 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C
8 min read
Computer Arithmetic | Set - 1
Negative Number Representation Sign Magnitude Sign magnitude is a very simple representation of negative numbers. In sign magnitude the first bit is dedicated to represent the sign and hence it is called sign bit. Sign bit ‘1’ represents negative sign. Sign bit ‘0’ represents positive sign. In sign
5 min read
Computer Arithmetic | Set - 2
FLOATING POINT ADDITION AND SUBTRACTION FLOATING POINT ADDITION To understand floating point addition, first we see addition of real numbers in decimal as same logic is applied in both cases. For example, we have to add 1.1 * 103 and 50. We cannot add these numbers directly. First, we need to align
4 min read
Introduction of Floating Point Representation
1. To convert the floating point into decimal, we have 3 elements in a 32-bit floating point representation: i) Sign ii) Exponent iii) Mantissa Sign bit is the first bit of the binary representation. '1' implies negative number and '0' implies positive number. Example: 110000011101000000000000000000
4 min read
Difference Between 1's Complement Representation and 2's Complement Representation Technique
In computer science, binary number representations like 1's complement and 2's complement are essential for performing arithmetic operations and encoding negative numbers in digital systems. Understanding the differences between these two techniques is crucial for knowing how computers handle signed
5 min read
Computer Organization | Booth's Algorithm
Booth algorithm gives a procedure for multiplying binary integers in signed 2’s complement representation in efficient way, i.e., less number of additions/subtractions required. It operates on the fact that strings of 0’s in the multiplier require no addition but just shifting and a string of 1’s in
7 min read
Restoring Division Algorithm For Unsigned Integer
The Restoring Division Algorithm is an integral procedure employed when calculating division on unsigned numbers. It is particularly beneficial in the digital computing application whereby base-two arithmetic is discrete. As a distinct from other algorithms, the Restoring Division Algorithm divides
6 min read
Non-Restoring Division For Unsigned Integer
The non-restoring division is a division technique for unsigned binary values that simplifies the procedure by eliminating the restoring phase. The non-restoring division is simpler and more effective than restoring division since it just employs addition and subtraction operations instead of restor
4 min read