Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner; // for user input
- public class Bin2Dec {
- /**
- * Program: Bin2Dec.java
- * Purpose: Convert binary number to decimal
- * Creator: Chris Clarke
- * Created: 21.09.2009
- * Modified: 25.03.2013 (Scanner)
- */
- public static int convertBin2Dec(String s) {
- int sum = 0;
- int multiplier = 0;
- for (int i = s.length()-1; i>=0; i--) { // work from right to left (1, 2, 4, 8 etc)
- if (s.charAt(i) == '1') {
- sum += Math.pow(2, multiplier); // add (2 ^ multiplier) to sum
- }//end if
- multiplier++; // increment multiplier
- }//end for
- return sum;
- }//end convertBin2Dec
- public static void main(String[] args) {
- if (args.length==1) { // user typed binary number as argument
- // method call outputs decimal number
- System.out.println( convertBin2Dec( args[0]));
- System.exit(0); // exit program
- }//end if
- Scanner scan = new Scanner(System.in); // create scanner object
- System.out.print("Enter binary number: "); // prompt
- String bin = scan.nextLine(); // get input from user
- System.out.println( convertBin2Dec( bin)); // method call outputs decimal number
- }//end main
- }//end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement