Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Using loops write a program that converts a binary integer number to its decimal form.
- * The input is entered as string. The output should be a variable of type long. */
- import java.util.Scanner;
- public class _13_BinaryToDecimalNumber {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter your Binary number on single line, without spaces: ");
- String binaryStr = scan.next();
- scan.close();
- // The Short way:
- // long decNum = Long.parseLong(binaryStr, 2);
- long decNum = convertBinaryNumberToDecimalNumber(binaryStr);
- System.out.println("That Binary number in Decimal system is: " + decNum);
- }
- private static long convertBinaryNumberToDecimalNumber(String binary) {
- // TODO Auto-generated method stub
- long sum = 0;
- long multiplier = 1;
- for (int i = binary.length() - 1; i >= 0; i--) {
- int digit = Integer.parseInt("" + binary.charAt(i));
- sum += digit * multiplier;
- multiplier *= 2;
- }
- return sum;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement