Quantcast
Channel: The Crazy Programmer
Viewing all articles
Browse latest Browse all 761

Program to Convert Binary to Decimal in Java

$
0
0

Here you will get program to convert binary to decimal in Java.

There are mainly two ways to convert a binary number to decimal number in Java.

1. By using parseInt() method of Integer class.
2. By using user defined logic.

Program to Convert Binary to Decimal in Java

By using Integer.parseInt()

Integer.parseInt() method takes two arguments. First argument is a string and second argument is the base or radix in which we have to convert the number. The output is the integer represented by the string argument in the specified radix. Below is the program for it.

 

import java.util.Scanner;

class BinaryToDecimal
{
        public static void main(String args[])
        {
            Scanner s=new Scanner(System.in);
            
            System.out.println("Enter a binary number:");

            String n=s.nextLine();
            
            System.out.println(Integer.parseInt(n,2));
        }
}

 

Without using Integer.parseInt()

In this method we have to define our own logic for converting binary number to decimal. The approach that we will use here is mentioned in below example.

binary to decimal example

Image Source

The program that implements above approach is mentioned below.

 

import java.util.Scanner;

class BinaryToDecimal
{
        public static void main(String args[])
        {
            Scanner s=new Scanner(System.in);
            
            System.out.println("Enter a binary number:");
            int n=s.nextInt();
            
            int decimal=0,p=0;
            
            while(n!=0)
            {
                decimal+=((n%10)*Math.pow(2,p));
                n=n/10;
                p++;
            }
            
            System.out.println(decimal);
        }
}

 

Output

Program to Convert Binary to Decimal in Java
If you found anything missing or incorrect in above programs then please mention it by commenting below.

The post Program to Convert Binary to Decimal in Java appeared first on The Crazy Programmer.


Viewing all articles
Browse latest Browse all 761

Trending Articles