You have the correct mathematical base:
11001b = (1 * 2 ^ 4) + (1 * 2 ^ 3) + (0 * 2 ^ 2) + (0 * 2 ^ 1) + (1 * 2 ^ 0)
It is true that you could calculate for each digit its corresponding power and then use Math.pow
, however this will make your code quite slow.
Instead note that you can build the number by "moving" the previous digit one unit and then adding the next. To "move" a digit a unit is multiplied by the base, thus in numbers with base 10:
resto
"1530" ac = 0 (acumulador)
"530" ac = 0 * 10 + 1 = 1
"30" ac = 1 * 10 + 5 = 15
"0" ac = 15 * 10 + 3 = 153
"" ac = 153 * 10 + 0 = 1530
For binary numbers it's the same story. Simply multiply the accumulator by 2 and add the numerical value of the character (0 or 1).
With this in mind, you can build the solution similar to the following:
import java.util.Scanner;
import static java.lang.System.out; // simplificar el "System.out.println"
public class Main {
public static void main (String args[])
{
Scanner scn = new Scanner(System.in);
out.print("Ingrese cadena binaria: ");
String cbin = scn.nextLine();
try {
long ret = parseBinary(cbin);
out.println(ret);
} catch (NumberFormatException e) { /* no es una cadena binaria */
out.println("La cadena contiene caracteres ilegales");
}
}
public static long parseBinary (String cbin)
{
if (cbin == null)
throw new IllegalArgumentException(); /* cbin no puede ser nulo */
long ac = 0;
for (int i = 0, l = cbin.length(); i < l; i++) {
char c = (char) (cbin.charAt(i) - '0'); /* obtiene el valor numérico */
if (c < 0) /* no es un digito */
throw new NumberFormatException();
if (c > 1) /* el digito es mayor a 1 */
throw new NumberFormatException();
ac = ac * 2 + c;
}
return ac;
}
}