The Wayback Machine - https://web.archive.org/web/20241006134749/https://www.geeksforgeeks.org/program-binary-decimal-conversion/
Open In App

Program for Binary To Decimal Conversion

Last Updated : 01 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Topics:
Solve Problem
Basic
51.5%
64.1K

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: 
 

binary2decimal

Below is the implementation of the above idea : 

C++




// C++ program to convert binary to decimal
#include <iostream>
using namespace std;
 
// Function to convert binary to decimal
int binaryToDecimal(int n)
{
    int num = n;
    int dec_value = 0;
 
    // Initializing base value to 1, i.e 2^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;
}
 
// Driver program to test above function
int main()
{
    int num = 10101001;
 
    cout << binaryToDecimal(num) << endl;
}


Java




// Java program to convert
// binary to decimal
 
// Function to convert
// binary to decimal
class GFG {
    static int binaryToDecimal(int n)
    {
        int num = n;
        int dec_value = 0;
 
        // Initializing base
        // value to 1, i.e 2^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;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int num = 10101001;
        System.out.println(binaryToDecimal(num));
    }
}
 
// This code is contributed by mits.


C#




// C# program to convert
// binary to decimal
 
// Function to convert
// binary to decimal
class GFG {
    public static int binaryToDecimal(int n)
    {
        int num = n;
        int dec_value = 0;
 
        // Initializing base1
        // value to 1, i.e 2^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;
    }
 
    // Driver Code
    public static void Main()
    {
        int num = 10101001;
 
        System.Console.Write(binaryToDecimal(num));
    }
}
 
// This code is contributed by mits.


Javascript




<script>
 
// JavaScript program to convert binary to decimal
 
// Function to convert binary to decimal
function binaryToDecimal(n)
{
    let num = n;
    let dec_value = 0;
 
    // Initializing base value to 1, i.e 2^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;
}
 
// Driver program to test above function
    let num = 10101001;
 
    document.write(binaryToDecimal(num) + "<br>");
 
 
// This code is contributed by Surbhi Tyagi
 
</script>


PHP




<?php
// PHP program to convert
// binary to decimal
 
// Function to convert
// binary to decimal
function binaryToDecimal($n)
{
    $num = $n;
    $dec_value = 0;
     
    // Initializing base value
    // to 1, i.e 2^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;
}
 
    // Driver Code
    $num = 10101001;
    echo binaryToDecimal($num), "\n";
 
// This code is contributed by ajit
?>


Python3




# Python3 program to convert
# binary to decimal
 
# Function to convert
# binary to decimal
def binaryToDecimal(n):
    num = n;
    dec_value = 0;
     
    # Initializing base
    # value to 1, i.e 2 ^ 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;
 
# Driver Code
num = 10101001;
print(binaryToDecimal(num));
 
# This code is contributed by mits


Output

169

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++




// C++ program to convert binary to decimal
// when input is represented as binary string.
#include <iostream>
#include <string>
using namespace std;
 
// Function to convert binary to decimal
int binaryToDecimal(string n)
{
    string num = n;
    int dec_value = 0;
 
    // Initializing base value to 1, i.e 2^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;
}
 
// Driver program to test above function
int main()
{
    string num = "10101001";
    cout << binaryToDecimal(num) << endl;
}


Java




// Java program to convert binary to
// decimal when input is represented
// as binary string.
import java.io.*;
 
class GFG {
 
    // Function to convert binary to decimal
    static int binaryToDecimal(String n)
    {
        String num = n;
        int dec_value = 0;
 
        // Initializing base value to 1,
        // i.e 2^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;
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        String num = new String("10101001");
        System.out.println(binaryToDecimal(num));
    }
}
 
// This code is contributed by Prerna Saini


C#




// C# program to convert binary to
// decimal when input is represented
// as binary string.
using System;
 
class GFG {
 
    // Function to convert binary to decimal
    static int binaryToDecimal(String n)
    {
        String num = n;
        int dec_value = 0;
 
        // Initializing base value to 1,
        // i.e 2^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;
    }
 
    // Driver Code
    public static void Main()
    {
        String num = "10101001";
        Console.WriteLine(binaryToDecimal(num));
    }
}
 
// This code is contribute by mits


Javascript




<script>
 
// Javascript program to convert binary to decimal
// when input is represented as binary string.
 
// Function to convert binary to decimal
function binaryToDecimal(n)
{
    let num = n;
    let dec_value = 0;
 
    // Initializing base value to 1, i.e 2^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;
}
 
// Driver program to test above function
 
    let num = "10101001";
    document.write(binaryToDecimal(num) + "<br>");
 
// This code is contributed by Mayank Tyagi
 
</script>


PHP




<?php
// PHP program to convert binary
// to decimal when input is
// represented as binary string.
 
// Function to convert
// binary to decimal
function binaryToDecimal($n)
{
    $num = $n;
    $dec_value = 0;
     
    // Initializing base
    // value to 1, i.e 2^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;
}
 
// Driver Code
$num = "10101001";
echo binaryToDecimal($num), "\n";
 
// This code is contributed by aj_36
?>


Python3




# Python3 program to convert binary
# to decimal when input is
# represented as binary string.
 
# Function to convert
# binary to decimal
def binaryToDecimal(n):
    num = n;
    dec_value = 0;
     
    # Initializing base
    # value to 1, i.e 2 ^ 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;
 
# Driver Code
num = "10101001";
print(binaryToDecimal(num));
 
# This code is contributed by mits


Output

169

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++




// C++ program to convert binary to decimal
#include <iostream>
using namespace std;
 
// Function to convert binary to decimal
int binaryToDecimal(int n)
{
    int dec_num = 0 ;
      int power = 0 ;
      while(n>0){
      if(n%10 == 1){ // extracting the last digit
        dec_num += (1<<power) ;
      }
      power++ ;
      n = n / 10 ;
    }
      return dec_num ;
}
 
// Driver program to test above function
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));
  }
}
 
// This code is contributed by aadityamaharshi21.


C#




using System;
 
public class Program
{
  // Function to convert binary to decimal
  public static int BinaryToDecimal(int n)
  {
    int dec_num = 0;
    int power = 0;
 
    while (n > 0)
    {
      if (n % 10 == 1) // extracting the last digit
      {
        dec_num += (1 << power);
      }
      power++;
      n = n / 10;
    }
 
    return dec_num;
  }
 
  // Driver program to test above function
  public static void Main()
  {
    int num = 10101001;
 
    Console.WriteLine(BinaryToDecimal(num));
  }
}


Javascript




// JavaScript program to convert binary to decimal
function binaryToDecimal(n) {
    let dec_num = 0;
    let power = 0;
    while (n > 0) {
        if (n % 10 === 1) { // extracting the last digit
            dec_num += (1 << power);
        }
        power++;
        n = Math.floor(n / 10);
    }
    return dec_num;
}
 
// Driver program to test the function
let num = 10101001;
 
console.log(binaryToDecimal(num));
 
// This code is contributed by adityamaharshi21.


Python3




# Python program to convert binary to decimal
import math
 
def binaryToDecimal(n):
    dec_num = 0
    power = 0
    while (n > 0):
        if (n % 10 == 1): # extracting the last digit
            dec_num += (1 << power)
        power = power + 1
        n = math.floor(n / 10)
         
    return dec_num
 
# Driver program to test the function
num = 10101001
 
print(binaryToDecimal(num))
 
# This code is contributed by Nidhi goel.


Output

169








Time complexity : O(log n)

Space complexity : O(1)

2) If the input is of string type :

C++




// C++ program to convert binary to decimal
// when input is represented as binary string.
#include <iostream>
#include <string>
using namespace std;
 
// Function to convert binary to decimal
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;
}
 
// Driver program to test above function
int main()
{
    string num = "10101001";
    cout << binaryToDecimal(num) << endl;
}


Java




// Java program to convert binary to decimal
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 {
    // Function to convert binary to decimal
    static int binaryToDecimal(string str)
    {
        int dec_num = 0;
        int power = 0;
        int n = str.Length;
 
        // Loop through the string from right to left
        for (int i = n - 1; i >= 0; i--) {
            // If the current character is '1', add 2^power
            // to the decimal number
            if (str[i] == '1') {
                dec_num += (1 << power);
            }
            power++;
        }
        return dec_num;
    }
 
    // Driver program to test above function
    static void Main(string[] args)
    {
        string num = "10101001";
        Console.WriteLine(binaryToDecimal(num));
    }
}


Javascript




// Javascript program to convert binary to decimal
// when input is represented as binary string.
 
 
// Function to convert binary to decimal
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;
}
 
// Driver program to test above function
 
let num = "10101001";
console.log(binaryToDecimal(num));
 
// The code is contributed by Arushi Goel.


Python3




# Python program to convert binary to decimal
def binaryToDecimal(str):
    dec_num = 0
    power = 0
    n = len(str)
 
    # Iterate through the string str
    for i in range(n - 1, -1, -1):
        if (str[i] == '1'):
            dec_num += (2 ** power)
        power += 1
   
    return dec_num
   
# Driver code
num = "10101001"
print(binaryToDecimal(num))


Output

169

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;
}
// This code is contributed by whysodarkbro


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;
}
 
// This code is contributed by whysodarkbro


Java




public class GFG {
    public static void main(String args[])
    {
        String binaryNumber = "1001";
        System.out.println(Integer.parseInt(binaryNumber, 2));
    }
}
 
// This code is contributed
// By Yash Kumar Arora


C#




using System;
 
class GFG {
     
public static void Main()
{
    int value = 1001;
    Console.Write(Convert.ToInt32(value.ToString(), 2));
}
}
 
// This code is contributed by SoumikMondal


Javascript




<script>
         
var binaryNumber = "1001";
document.write(parseInt(binaryNumber, 2));
 
// This code contributed by Princi Singh
</script>


Python3




n = input()
 
# Convert n to base 2
s = int(n, 2)
 
print(s)


Output

9

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() {
    // Create a string to store the binary number
    std::string binaryNumber;
 
    // Prompt the user to enter a binary number
    std::cout << "Enter Binary number: ";
 
    // Read the entire line as input
    std::getline(std::cin, binaryNumber);
 
    // Convert binary to decimal
    int decimalNumber = 0;
    for (size_t i = 0; i < binaryNumber.length(); i++) {
        decimalNumber = decimalNumber * 2 + (binaryNumber[i] - '0');
    }
 
    // Print the decimal number
    std::cout << "Decimal: " << decimalNumber << std::endl;
 
    return 0;
}


Java




import java.util.Scanner;
 
public class BinaryToDecimal {
    public static void main(String[] args) {
        // Create a Scanner object to take user input
        Scanner scanner = new Scanner(System.in);
 
        // Prompt the user to enter a binary number
        System.out.print("Enter Binary number: ");
         
        // Read the entire line as input
        String binaryNumber = scanner.nextLine();
 
        // Convert binary to decimal
        int decimalNumber = 1;
        for (int i = 0; i < binaryNumber.length() - 1; i++) {
            decimalNumber = decimalNumber * 2 + Character.getNumericValue(binaryNumber.charAt(i + 1));
        }
 
        // Print the decimal number
        System.out.print("Decimal: ");
        System.out.println(decimalNumber);
 
        // Close the Scanner
        scanner.close();
    }
}


C#




using System;
 
class Program {
    static void Main(string[] args)
    {
        // Create a string to store the binary number
        string binaryNumber;
 
        // Prompt the user to enter a binary number
        Console.Write("Enter Binary number: ");
 
        // Read the entire line as input
        binaryNumber = Console.ReadLine();
 
        // Check if input is empty
        if (string.IsNullOrEmpty(binaryNumber)) {
            Console.WriteLine("Decimal: 0");
            return; // Exit the program
        }
 
        // Convert binary to decimal
        int decimalNumber = 0;
        for (int i = 0; i < binaryNumber.Length; i++) {
            decimalNumber = decimalNumber * 2
                            + (binaryNumber[i] - '0');
        }
 
        // Print the decimal number
        Console.WriteLine("Decimal: " + decimalNumber);
    }
}


Javascript




// Prompt the user to enter a binary number
var n = prompt("Enter Binary number: ");
 
// Initialize the decimal variable to store the result
var dec = 1;
 
// Iterate through each digit of the binary number
for (var i = 0; i < n.length - 1; i++) {
// Update the decimal value using the formula: dec = dec * 2 + currentBinaryDigit
dec = dec * 2 + parseInt(n[i + 1]);
}
 
// Display the decimal result
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)
 
# This code is contributed by Jeevani Anumandla


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.

 



Previous Article
Next Article

Similar Reads

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 Example: If the decimal number is 10. Step 1: Remaind
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 = "" Declare ch while n > 0 if (n & 1) == 0 ch
8 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 variable dec_value. At the time of extracting dig
11 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 10-15 are represented by characters from A - F.
8 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, the binary number system uses two digits 0 and 1
10 min read
Decimal to octal conversion with minimum use of arithmetic operators
Given a decimal number n without floating-point. The problem is to convert the decimal number to octal number with minimum use of arithmetic operators. Examples: Input : n = 10 Output : 12 12 is octal equivalent of decimal 10. Input : n = 151 Output : 227 Approach: Following are the steps: Perform decimal to binary conversion without using arithmet
8 min read
Gray to Binary and Binary to Gray conversion
Binary Number is the default way to store numbers, but in many applications, binary numbers are difficult to use and a variety of binary numbers is needed. This is where Gray codes are very useful. Gray code has a property that two successive numbers differ in only one bit because of this property gray code does the cycling through various states w
13 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. Examples Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. Approach: The idea to recursively trav
7 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. Example: Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. Approach: The idea is to recursively t
7 min read
Sum of decimal equivalents of binary node values in each level of a Binary Tree
Given a Binary Tree consisting of nodes with values 0 and 1 only, the task is to find the total sum of the decimal equivalents of the binary numbers formed by connecting nodes at the same level from left to right, on each level. Examples: Input: Below is the given Tree: 0 / \ 1 0 / \ / \ 0 1 1 1Output: 9Explanation: Binary number formed at level 1
15 min read
8086 program to convert a 16 bit decimal number to binary
Problem: We are given a 16 bit decimal number we have to print the number in binary format Examples: Input: d1 = 16 Output: 10000 Input: d1 = 7 Output: 111 Explanation: Load the value stored into registerDivide the value by 2 to convert it to binaryPush the remainder into the stackIncrease the countRepeat the steps until the value of the register i
2 min read
Program to convert a Binary Number to Hexa-Decimal Number
Given a Binary Number, the task is to convert this Binary number to its equivalent Hexa-Decimal Number.Examples: Input: 100000101111 Output: 82F Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1111. Here, 1000 is equivalent to 8, 0010 is equivalent to 2 and 1111 is equivalent to F Therefore, the number becomes 82FInput:10101
10 min read
Javascript Program To Find Decimal Equivalent Of Binary Linked List
Given a singly linked list of 0s and 1s find its decimal equivalent. Input: 0->0->0->1->1->0->0->1->0Output: 50 Input: 1->0->0Output: 4The decimal value of an empty linked list is considered as 0. Initialize the result as 0. Traverse the linked list and for each node, multiply the result by 2 and add the node's data to
3 min read
Conversion of Binary number to Base 4 system
We all know that, [Tex]2^2 [/Tex]= [Tex]4^1 [/Tex]. In other words, single digit in base 4 can be represented using 2 digits in base 2. Base 2 has digits 0 and 1. Similarly base 4 has digits 0, 1, 2 and 3. Algorithm for Binary to Base 4 Conversion Beginning from right, group the digits of binary (base 2) number into group of two. Write the base 4 e
1 min read
Number of substrings with odd decimal value in a binary string
Given a binary string containing only 0's and 1's. Write a program to find number of sub-strings of this string whose decimal representation is odd. Examples : Input : 101 Output : 3 Explanation : Substrings with odd decimal representation are: {1, 1, 101} Input : 1101 Output : 6 Explanation : Substrings with odd decimal representation are: {1, 1,
6 min read
Decimal representation of given binary string is divisible by 20 or not
The problem is to check whether the decimal representation of the given binary number is divisible by 20 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or the minimum numbers of multiplication and division operations. No leadings 0’s are there in the input. Ex
14 min read
Sum of decimal equivalent of all possible pairs of Binary representation of a Number
Given a number N. The task is to find the sum of the decimal equivalent of all the pairs formed from the binary representation of the given number. Examples: Input: N = 4 Output: 4 Binary equivalent of 4 is 100. All possible pairs are 10, 10, 00 and their decimal equivalent are 2, 2, 0 respectively. So, 2 + 2+ 0 = 4 Input: N = 11 Output: 13 All pos
5 min read
Decimal to Binary using recursion and without using power operator
Given an integer N, the task is convert and print the binary equaiva;ent of N.Examples: Input: N = 13 Output: 1101Input: N = 15 Output: 1111 Approach Write a recursive function that takes an argument N and recursively calls itself with the value N / 2 as the new argument and prints N % 2 after the call. The base condition will be when N = 0, simply
3 min read
Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
Given a binary-valued Undirected Graph with V vertices and E edges, the task is to find the maximum decimal equivalent among all the connected components of the graph. A binary-valued graph can be considered as having only binary numbers (0 or 1) as the vertex values. Examples: Input: E = 4, V = 7 Output: 3 Explanation: Decimal equivalents of the c
14 min read
Check if decimal representation of Binary String is divisible by 9 or not
Given a binary string S of length N, the task is to check if the decimal representation of the binary string is divisible by 9 or not. Examples: Input: S = 1010001Output:YesExplanation: The decimal representation of the binary string S is 81, which is divisible by 9. Therefore, the required output is Yes. Input: S = 1010011Output: NoExplanation: Th
12 min read
Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted
Given an array arr[] consisting of N positive integers, the task is to rearrange the array such that the reversed binary representation of all the array elements is sorted. If the decimal equivalent of reversed binary representations of two or more array elements is equal, then the original value is taken into consideration while rearranging the ar
13 min read
Check if level-wise Decimal equivalent of Binary Tree forms a Monotonic sequence or not
Given the root of a binary tree in which all nodes has values either 0 or 1, the task is to check if the level-wise decimal equivalent of given Tree forms a monotonic sequence.or not. A sequence is monotonic if it is either monotone increasing or monotone decreasing. A sequence nums is monotone increasing if for all i <= j, nums[i] <= nums[j]
15+ min read
Convert Binary to Decimal in Swift
In computers, we use two main number systems: binary (with 0s and 1s) and decimal (with numbers from 0 to 9). Converting binary numbers (like 1010) into decimal numbers (like 10) is a common task in programming. In this article, we'll learn how to do this in Swift, a programming language developed by Apple. Problem StatementThe problem is to conver
2 min read
Counting even decimal value substrings in a binary string
Given a binary string of size N. Count all substring that have even decimal value considering binary to decimal conversion from left to right (For example a substring "1011" is treated as 13) Examples : Input : 101Output : 2Explanation : Substring are : 1, 10, 101, 0, 01, 1 In decimal form : 1, 1, 3, 0, 2, 1 There are only 2 even decimal value subs
9 min read
BCD or Binary Coded Decimal
Binary Coded Decimal, or BCD, is another process for converting decimal numbers into their binary equivalents. It is a form of binary encoding where each digit in a decimal number is represented in the form of bits.This encoding can be done in either 4-bit or 8-bit (usually 4-bit is preferred).It is a fast and efficient system that converts the dec
3 min read
Decimal Equivalent of Binary Linked List
Given a singly linked list of 0s and 1s find its decimal equivalent. Input : 0->0->0->1->1->0->0->1->0 Output : 50 Input : 1->0->0 Output : 4The decimal value of an empty linked list is considered as 0. Recommended PracticeDecimal Equivalent of Binary Linked ListTry It!Initialize the result as 0. Traverse the linked li
10 min read
Maximum decimal value path in a binary matrix
Given binary square matrix [n*n]. Find maximum integer value in a path from top left to bottom right. We compute integer value using bits of traversed path. We start at index [0,0] and end at index [n-1][n-1]. from index [i, j], we can move [i, j+1] or [i+1, j]. Examples: Input : mat[][] = {{1, 1, 0, 1}, {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 1, 1}} Ou
14 min read
Convert Binary fraction to Decimal
Given an string of binary number n. Convert binary fractional n into it's decimal equivalent. Examples: Input: n = 110.101 Output: 6.625 Input: n = 101.1101 Output: 5.8125We strongly recommend that you click here and practice it, before moving on to the solution. Following are the steps of converting binary fractional to decimal. A) Convert the int
6 min read
Queries for decimal values of subarrays of a binary array
Given a binary array arr[], we to find the number represented by the subarray a[l..r]. There are multiple such queries. Examples: Input : arr[] = {1, 0, 1, 0, 1, 1}; l = 2, r = 4 l = 4, r = 5 Output : 5 3 Subarray 2 to 4 is 101 which is 5 in decimal. Subarray 4 to 5 is 11 which is 3 in decimal. Input : arr[] = {1, 1, 1} l = 0, r = 2 l = 1, r = 2 Ou
11 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 > 1, later perform n % 1 to get MSB of converted binary number. Example :- 7 1). 7/
4 min read