Advertisement
dimipan80

Binary to Decimal Number

Aug 8th, 2014
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1. /* Using loops write a program that converts a binary integer number to its decimal form.
  2.  * The input is entered as string. The output should be a variable of type long. */
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class _13_BinaryToDecimalNumber {
  7.  
  8.     public static void main(String[] args) {
  9.         // TODO Auto-generated method stub
  10.         Scanner scan = new Scanner(System.in);
  11.         System.out.print("Enter your Binary number on single line, without spaces: ");
  12.         String binaryStr = scan.next();
  13.         scan.close();
  14.  
  15.         // The Short way:
  16.         // long decNum = Long.parseLong(binaryStr, 2);
  17.  
  18.         long decNum = convertBinaryNumberToDecimalNumber(binaryStr);
  19.  
  20.         System.out.println("That Binary number in Decimal system is: " + decNum);
  21.     }
  22.  
  23.     private static long convertBinaryNumberToDecimalNumber(String binary) {
  24.         // TODO Auto-generated method stub
  25.         long sum = 0;
  26.         long multiplier = 1;
  27.         for (int i = binary.length() - 1; i >= 0; i--) {
  28.             int digit = Integer.parseInt("" + binary.charAt(i));
  29.             sum += digit * multiplier;
  30.             multiplier *= 2;
  31.         }
  32.  
  33.         return sum;
  34.     }
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement