Approach-1
// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science )
import java.util.Scanner;
class BinToDec {
public static void main(String[ ] args) {
System.out.print("Enter a Binary Number: ");
String binary = new Scanner(System.in).next();
System.out.println("Equivalent Decimal Number: " + Integer.parseInt(binary , 2));
}
}
OUTPUT
cmd-> javac BinToDec.java
cmd-> java BinToDec
Enter a Binary Number: 101011
Equivalent Decimal Number: 43
Approach-2
// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science )
import java.lang.Math;
import java.util.Scanner;
class BinaryToDecimal {
static int convertToDec(String bin) {
int[] binArray = new int[1024];
int eqv_dec = 0;
for (int i = bin.length() - 1; i >= 0; i--) {
binArray[i] = Character.getNumericValue(bin.charAt(i));
}
for (int i = 0; i < bin.length(); i++) {
if (binArray[i] == 1)
eqv_dec += (int)Math.pow(2, bin.length()-1 - i);
else
continue;
}
return eqv_dec;
}
// Driver Code!
public static void main(String[] args) {
System.out.print("Enter Binary Number: ");
String bin = new Scanner(System.in).next();
System.out.println("Given Binary: " + bin);
int eqv_dec = convertToDec(bin);
System.out.println("Equivalent Decimal Number: " + eqv_dec);
}
}
OUTPUT
cmd-> javac DecimalToBinary.java
cmd-> java DecimalToBinary
Enter Binary Number: 101010110
Given Binary: 101010110
Equivalent Decimal Number: 342
Also read my full article at GeeksForGeeks