Monday, December 12, 2011

Convert Binary Integer to Decimal in Java?

Hi I am trying to write an app that inputs an integer containing only 0s and 1s (a binary integer) and prints its decimal equivalent. I am aware that there are some very short ways to do this but as a beginner I am writing this to show the process.





I want to use a loop and keep dividing the binary number by 10 and keep multiplying the remainder with increasing powers of 2. I have to keep a variable 'sum' to store the sum of the acquired numbers and terminate the loop when all the digits have been divided. I will have the decimal number stored in 'sum'. Any help will be greatly appreciated! thanks :)|||Here's code from my computer class, final exam. It has nice GUI, but it needs a file called numTout.txt in the same directory (Had something to do with the fact that my teacher wanted file I/O somewhere). Ignore the file chooser at the beginning or pick with it numTout.txt if it isnt in the same directory. Other than that, examine my converter methods, they are advanced but really efficient. They use logical left- and right-shifts, which are bitwise shift operations. Let's just say they work.





/**


* @(#)ExamenVer2.java


*


*


* @author


* @version 1.00 2010/1/13


*/


import java.io.*;


import java.awt.*;


import java.awt.event.*;


import javax.swing.*;








public class ExamenVer2 extends JFrame implements ActionListener{


static final int debug=0;





//D茅claration des fichiers et des Buffered streams


File fichierTout=new File("numTout.txt"), fichierConverti=new File("numConverti.txt");


BufferedReader lireFichier;


BufferedWriter ecrireFichier;


static final int intwidth=Integer.SIZE;/*Pour savoir le integer width, utile pour savoir le


nombre de left et rightshifts n茅cessaires*/


static final String newline=System.getProperty("line.separat鈥?br>




//GUI


JLabel eti1, eti2;


JPanel hautPanel,midPanel,basPanel;


JTextField montreBinaire, montreDecimal;


JButton prochain,convbindec,convdecbin;


BorderLayout bLayout;





public ExamenVer2(){


super("Converter de formats de nombres");





// IO ****************************************鈥?br>

JFileChooser jfk=new JFileChooser(System.getProperty("user.di鈥?br>

if(jfk.showOpenDialog(null)==JFileChoos鈥?br>

fichierTout=jfk.getSelectedFile();


}


if(!fichierTout.exists()){


System.out.println("Fichier de lecture introuvable");


System.exit(1);//Error code 1


}


if(!fichierConverti.exists()){


try{


fichierConverti.createNewFile();


}catch(IOException ioe){


System.out.println("Fichier numConverti.txt impossible 脿 cr茅er");


System.exit(2);//Error code 2


}


}





//Instanciation de IO et Error handling


try{


lireFichier=new BufferedReader(new FileReader(fichierTout));


ecrireFichier=new BufferedWriter(new FileWriter(fichierConverti));


}catch(FileNotFoundException fnfe){


System.out.println("Fichier de lecture introuvable");


System.exit(1);//Error code 1


}catch(IOException ioe){


System.out.println("Impossible de lire ou d'茅crire");


System.exit(3);//Error code 3


}


// IO ****************************************鈥?br>




//GUI Objets


montreBinaire=new JTextField("0",32);


montreDecimal=new JTextField("0",20);


eti1=new JLabel("Binaire");


eti2=new JLabel("D\u00e9cimal");


prochain=new JButton("Prochain Nombre (File I/O)");


convbindec=new JButton("Binaire -%26gt; D\u00e9cimal");


convdecbin=new JButton("D\u00e9cimal -%26gt; Binaire");


hautPanel=new JPanel();


midPanel=new JPanel();


basPanel=new JPanel();


//Listeners


prochain.addActionListener(this);


convbindec.addActionListener(this);


convdecbin.addActionListener(this);


//Layouts


hautPanel.setLayout(new FlowLayout());


midPanel.setLayout(new FlowLayout());


basPanel.setLayout(new FlowLayout());


bLayout=new BorderLayout();


this.setLayout(bLayout);


hautPanel.add(convbindec);


hautPanel.add(convdecbin);


midPanel.add(prochain);


basPanel.add(montreBinaire);


basPanel.add(eti1);


basPanel.add(montreDecimal);


basPanel.add(eti2);


this.add(hautPanel,BorderLayout.NORT鈥?br>

this.add(midPanel,BorderLayout.CENTE鈥?br>

this.add(basPanel,BorderLayout.SOUTH鈥?br>




//De fin


this.setSize (800,200);


this.setDefaultCloseOperation(JFrame鈥?br>

this.setVisible(true);


}








//Main


public static void main(String args[]){


ExamenVer2 Exam=new ExamenVer2();


}//Fin de main








//actionPerformed


public void actionPerformed(ActionEvent actionEvent){


String ligne="";


if(actionEvent.getSource()==prochain){


try{


ligne=lireFichier.readLine();


}catch(IOException ioe){


System.out.println("Erreur d'IO: "+ioe.getMessage());


System.exit(4);//Error code 4


}





if(ligne==null||ligne==""){


return;//Rien 脿 faire


}else{


ligne=ligne.trim();


if(debug%26gt;0){


System.out.println(ligne);//Et poursuit.


}


}





if(ligne.startsWith("b")){//Binaire鈥?on le convertit vers d茅cimal


ligne=ligne.substring(1).trim();//鈥?la lettre de d茅but


try{


ecrireFichier.write(ligne+" b-%26gt;d ");//脡crire la premi猫re partie du output


}catch(IOException ioe){


System.out.println("Erreur d'IO: "+ioe.getMessage());


System.exit(5);//Error code 5


}








String dec=binadec(ligne);





montreDecimal.setText(dec);


montreBinaire.setText(ligne);


try{


ecrireFichier.write(dec+newline);鈥?le nombre converti


}catch(IO

No comments:

Post a Comment