In the previous article, we have discussed Java Program for Decimal to Hexadecimal
In this article we will see how to convert Binary to Decimal.
Program for Binary to Decimal
So, before going into the program directly, let’s know about binary and decimal.
Binary:
Binary number mainly consists of only two numbers i.e. 0 and 1. The base address of the binary number is 2. For low voltage signal the value will 0 and for the high voltage signal the value will 1.
Example: (1001)2, (111000)2
Where 2 is the base. i.e ( )2
Decimal:
Decimal number mainly defines the base of 10 in the number system. This number is basically consists of 10(ten) single digits like 0,1,2,3,4,5,6,7,8 and 9 with base 10. It is also known as a position value system.
Example: (183)10, (321)10
Where, 10 is the base. i.e ( )10
Now, let’s see different ways to do it.
Method-1: Java Program for Binary to Decimal By using Integer.ParseInt()
In this method we will use the inbuilt method Integer.ParseInt()
of Integer class.
Approach:
- Take a binary value and store it in an integer variable say
binaryString
. - Pass this binary value to
Integer.ParseInt()
method. - Then store the converted decimal value in an integer output variable say
decimal
.
Program:
import java.util.*; public class BinaryToDecimal { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the binary string : "); String binaryString=sc.nextLine(); int decimal=Integer.parseInt(binaryString,2); System.out.println("The conversion of number " +binaryString+ " is : "+decimal); } }
Output: Enter the binary string : 10111 The conversion of number 1011 is : 23
Method-2: Java Program for Binary to Decimal By using custom logic method
In this method we will convert the binary to decimal value by using custom method.
Approach:
- Take binary value as input from user.
- Pass this binary value to user defined method
getDecimal()
method where our binary to decimal conversion logic is present. - Then return the converted decimal value in long variable say
decimal
as output.
Program:
import java.util.*; public class Main { public static long getDecimal(long binary) { long decimal = 0; long n = 0; while(true){ if(binary == 0) { break; } else { long temp = binary%10; decimal += temp*Math.pow(2, n); binary = binary/10; n++; } } return decimal; } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter two binary value : "); long n1=sc.nextLong(); long n2=sc.nextLong(); System.out.println("Decimal of "+n1+" is: "+getDecimal(n1)); System.out.println("Decimal of "+n2+" is: "+getDecimal(n2)); } }
Output: Enter two binary value : 10111 11 Decimal of 10111 is: 23 Decimal of 11 is: 3
Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.
Related Java Programs: