Convert Binary to Decimal in netbeans

0

As I convert from binary to decimal through recursion friends, I am implementing my code in this way, but from here I stayed:

Public class binarioDecimal{
public int binarioADecimal(int v[], int n){
  if(n<0){
    return 0;
  }else{
    return binarioDecimal(binario, n-1);
  }
}
    
asked by Oswaldo 11.10.2017 в 02:32
source

1 answer

0

Your code practically does not say anything, in fact it is completely wrong since at no time do you declare the variable "binary" that you send in the 2nd return and you also call a constructor that has not been declared.

I leave you an option that is more similar to what you tried to do

public class BinaryToDecimal {
  // variable global que contendra el valor del decimal
  private int decimalValue = 0;
  //recibe como parametros el numero binario almacenado en un array y el 
  indice con el que trabajara
  public int convertBinaryToDecimal( int[] binaryValue, int index ) {
  //comprueba que el indice no sea menor que 0
  if(index >= 0) {
    //comprueba que el valor del binario sea 1 en la posicion del indice
    if(binaryValue[index] == 1) {
      // suma el valor del binario correspondiente al indice y lo guarda en decimalValue
      // ten en cuenta que el valor de un digito binario depende de la posicion en la que este en el arreglo
      // 
      // Ejemplo
      // 
      // indice del arreglo        0           2          3           4           5           6            7
      // valor del binario        2^6         2^5        2^4         2^3         2^2         2^1          2^0
      // 
      // Nota que se le resta 1 al numero de elementos del arreglo ya que un array comienza desde la posicion 0
      //
      decimalValue = (int) (decimalValue + (Math.pow(2, ( (binaryValue.length-1) - index ))));
      //Recursividad restandole 1 al indice para trabajar con el indice anterior
      convertBinaryToDecimal(binaryValue, index-1);
    }
    //en caso de que el valor del binario sea 0 en la posicion del indice no hace falta hacer ninguna operacion
    else{
    //Recursividad restandole 1 al indice para trabajar con el indice anterior
      convertBinaryToDecimal(binaryValue, index-1);
    }
  }
  //devuelve el valor del binario en Decimal
  return decimalValue;
  }
}

To call it you only need to pass the binary contained in an array and the index of the last position of the array, for example

public class Principal {
  public static void main(String[] args) {
    int binary [] = {1,0,1,0,0,0,0,0,0,1,0,1};
    BinaryToDecimal btd = new BinaryToDecimal();
    int valueDecimal = btd.convertBinaryToDecimal(binary, binary.length-1);
    System.out.println("el valor del binario en decimal es: "+ valueDecimal);
  }
}
    
answered by 11.10.2017 / 23:35
source