Problemas ao converter binario para decimal

2 respostas
dioni_deivid_dors
/**
 * Por exemplo: suponha um número constituído de 4 bits: 1101
 * Para obter em formato decimal, seguinte cálculo: 
 *    1*20 + 0*21 + 1*22 + 1*23
 *
 * @author Dioni deivid
 */


int binarioDecimal = 0;
        int contador = 0;
        
        String aux = JOptionPane.showInputDialog("informe um numero binario");
        
       
        for (int i = (aux.length() - 1); i >= 0; i--) {
       
         binarioDecimal += aux.charAt(i) * (Math.pow(2, contador));
            
                    
            contador++;
         }
        System.out.println("resultado em decimal:"+binarioDecimal);
      // ele está retornando  o numero da tabela ascII o 0 e 1, 48 e 49, e nao os 0 e 1...  aux.charAt(i)

2 Respostas

J

Ola dioni deivid dors de uma olhada nessa classe que desenvolvi a algum tempo, ele pode ser útil para você fazer essas conversões.

https://github.com/johnidm/ExemploComandosAPDU/blob/master/src/br/com/johnidouglas/APDUUtils.java

weslly99
Faz assim
import javax.swing.JOptionPane;

public class BinarioPDecimal {
	
	public static void main(String[] args) {
		int binarioDecimal = 0;  
        int controle = 1;
      		
       String aux =JOptionPane.showInputDialog("informe um numero binario"); 
       String n = aux;
      
       for (int i = 0; i <= aux.length();i++) {  
    	  
    	   //se n for maior q n.length() entregue o ultimo numero 
    	   String g = n.length() > 0? n.substring(n.length()-1): "0";
    	   
    	   //n recebe n - o numero entregue a variavel g
    	   n = n.length() > 0? n.substring(0,n.length()-1): "";
    	   
    	  //calcula
    	   binarioDecimal += controle * Integer.parseInt(g);
    	   
    	   controle*=2;
         }  
        JOptionPane.showMessageDialog(null, "resultado em decimal: "+binarioDecimal);  
	
	}
}

ou faz assim

import javax.swing.JOptionPane;

public class BinarioPDecimal {
	
	public static void main(String[] args) {
	
      		
       String aux =JOptionPane.showInputDialog("informe um numero binario"); 
   
     
       int binarioDecimal = Integer.parseInt(aux, 2);
      
       JOptionPane.showMessageDialog(null, "resultado em decimal: "+binarioDecimal);  
      
	}
}
Criado 25 de maio de 2013
Ultima resposta 27 de mai. de 2013
Respostas 2
Participantes 3