Convert Binary to Decimal in Java
Here you will get program to convert binary to decimal in java programing. We will convert Binary number to Decimal number in Java by using 2 different methods:
- using Integer.parseInt() method
- without using Integer.parseInt()
using Integer.parseInt Syntax:
int DecimalNumber = Integer.parseInt(BinaryNumber, 2);
For example:
int DecimalNumber = Integer.parseInt(“1100”, 2);
System.out.println(“Decimal Number of 1100 is: ” + DecimalNumber);
// Output: Decimal Number of 1100 is: 12
Convert Binary to decimal in Java using Integer.parseInt
1 2 3 4 5 6 7 8 9 10 11 12 | import java.util.*; public class BinarytoDecimal { public static void main(String ar[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter Binary Number : "); String st = sc.next(); int num= Integer.parseInt(st,2); System.out.println("Decimal -> "+num); } } |
Output
Binary to decimal without using Integer.parseInt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.*; public class BinarytoDecimal2 { public static void main(String ar[]) { int DecimalNum = 0; int pow = 0; Scanner sc = new Scanner(System.in); System.out.print("Enter Binary Number : "); String BinaryNum = sc.nextLine(); for(int k = BinaryNum.length() - 1; k >= 0; k--) { if(BinaryNum.charAt(k) == '1') { DecimalNum += Math.pow(2, pow); } pow++; } System.out.println("Decimal Number is: " + DecimalNum); sc.close(); } } |
Output
Check out our other Java Programming Examples