how do I make a binary to decimal converter?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • the Pantz

    #1

    how do I make a binary to decimal converter?

    i need to use integer division to extract the digits. This is more of a math issue than a programming issue i think.This is what i have so far:
    Code:
    import java.util.Scanner;
    
    public class TremorinKeithA2Q2 {
    
    public static void main(String[] args) {
    
    	String biInput="";
    	int len;
    	int biPow;
    	int i;
    	int product;
    	int bi = 0;
    	int lastDigit;
    	int trunc;
    
    		Scanner kbd = new Scanner(System.in);
    
    		while(bi!=-1){
    	    	System.out.println("Enter a binary number");
    			biInput = kbd.next();
    			bi = Integer.parseInt(biInput);
    			len =biInput.length();
    
    			for(i = len-1; i>=0; i--){
    				biPow= (int)Math.pow(2,i);
    				lastDigit = bi%10;
    				product = lastDigit * biPow;
    				trunc = bi/10;
    
    		   }
    
    
    
    
    }
    }
    }
    I don't know where to go from here.
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    The logic is wrong. I suggest you modify this logic.

    Regards
    Dheeraj Joshi

    Comment

    • Nepomuk
      Recognized Expert Specialist
      • Aug 2007
      • 3111

      #3
      Let's have a look at what this algorithm has to do.

      Say, we have the input 101010 and should turn this into a decimal number. Now, 101010 means 1*32 + 0*16 + 1*8 + 0*4 + 1*2 + 0*1, so we'll start at the last digit and work our way forward from there.

      As the computer is using an integer, which works on the basis of 10, to get the last digit use
      Code:
      biInput % 10
      In this case, this will give you the digit 0.

      Then, you want to get to the next digit. There are several ways of doing that, but the simplest method is to remove the last digit (here: the 0) and then check which is the new last digit. It's not difficult. :-)

      Greetings,
      Nepomuk

      Comment

      • santaji
        New Member
        • Jul 2009
        • 7

        #4
        • Multiplication is happening in reverse direction
        • "product" variable is not updated to do sum of previous state and current state
        • "bi" variable is not updated even after getting last digit

        Comment

        Working...