Program that convert binary to decimal

1

I try to make a program that takes a string, evaluates each character and performs the corresponding operation according to its position to reach the result.

this is what I have, but I can not find the correct algorithm

import java.util.Scanner;
public class prueba {

public static void main (String...s) {
    Scanner sc = new Scanner (System.in);
    String b;
    System.out.print ( "cadena: ");
    b = sc.nextLine();
    int i = 0;
    int potencia = b.length() - 1;
    int dig=0;
    int res = 0;
    while (i < b.length()) {
        int lo = dig;
        dig= Character.getNumericValue(b.charAt(i));

        lo = (int) ( Math.pow(2, potencia)*dig);
        res = lo+dig;
        i++;
        potencia--;
    }
    System.out.print (res);

}
}
    
asked by Star Hikari 02.11.2018 в 07:37
source

3 answers

1

You only need to change some things in your code, res = lo + dig; I do not see the reason to add that values, you should only add to res the result of your operation:

int i = 0;
int potencia = b.length() - 1;
int dig = 0;
int res = 0;
while (i < b.length()) {
    dig = Character.getNumericValue(b.charAt(i));
    res += (int) (Math.pow(2, potencia) * dig);
    potencia--;
    i++;
}
System.out.print(res);

You have to add res your result so that it accumulates for each number, greetings.

    
answered by 02.11.2018 / 08:25
source
0

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;      
    }
}
    
answered by 02.11.2018 в 10:57
0
import java.util.Scanner;

public class calBin {

public static void main (String[] Args) {

    Scanner teclado = new Scanner(System.in);

    //Se recoge el valor que queremos calcular
    System.out.println("Introduce un numero");
    int num = teclado.nextInt();
    teclado.close();

    int coc=0 ;     //variable utilizada en el primer bucle
    int coc2=0;     // variable utilizada en el segundo
    int num1=num;       // Copia de la variable num utilizada en el segundo bucle
    int i = 0;      // Variable que contendra el numero de veces que tiene que dividir un numero

    /* 
     * Bucle para obtener el numero de veces que se divide un numero entre 2
     * El valor sera almacenado en la variable i
    */
    for(i=0; coc!=1; i++){
        coc = num1/2;
        num1 = coc;
    }

    int [] array;       // Se declara la array
    i = i++;        // Se le suma un valor a i para poder almacenar el 1 del principio del binario
    array = new int[i+1];       // Se le da tamaño a la array, que sera i+1
    array[i]=1;     // Se le da valor 1 al ultimo valor de la array, que sera el primer digito del binario

    /* 
     * Bucle que almacena en la array los resultados de la division entre 2
     * de un numero hasta que el numero sea uno. 
    */
    for(int e = 0; coc2!=1; e++) {
        coc2 = num/2;
        int res = num%2;
        num = coc2;
        array[e]=res;
    }

    // Bucle que va mostrando los valores de la array en una misma linea por consola
    for(int y = 0; y<=i; y++) {
        System.out.print(array[i-y]);
    }
}

}

    
answered by 02.11.2018 в 11:03