简体   繁体   中英

(java) convert a decimal number to binary without using parseint

I am new to java and I was learning how to convert from binary to decimal and vice versa. In the case of binary to decimal, I found out that I could use parseint, but I saw other methods that didn't use it, so I tried to implement them into my code, but it didn't work for me and I got stumped.

How would I be able to use a different method for calculating binary to decimal and implement it into my code?

Here is my code:

import java.util.Scanner;
class BinaryToDecimal {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String binaryString;
        char choice;
        String nextLine = "Empty";
        int i = 0;
        choice = 'Y';
        try {
            do {


                System.out.print("Enter a binary number: ");
                binaryString = sc.nextLine();
                //Find the string count
                int count = binaryString.length();
                for (int j = 0; j< count; j++)
                {
                    if (binaryString.charAt(j) != '1' &&  binaryString.charAt(j) != '0')
                    {
                        System.out.print("Enter a binary number: ");
                        binaryString = sc.nextLine();
                        count = binaryString.length();
                        j=0;
                    }

                }
                i = Integer.parseInt(binaryString);

                if (i>0)
                    System.out.println("The decimal number is: " + Integer.parseInt(binaryString, 2));

                System.out.println("Continue using the calculator? Only input Y or N");
                String ln = sc.next();
                if(ln.length()==1){
                    choice = ln.charAt(0);
                }
                else{
                    choice = 'N';
                }
                if (sc.hasNextLine()) {
                    nextLine = sc.nextLine();

                }

            } while (choice == 'Y');


        } catch (NumberFormatException nfe) {
            System.out.println("Invalid input");
        }

    }
}

Binary math involves adding 1 and multiplying by 2. I would use a regular expression to test if the input is valid. I would use an infinite loop and break when the user gives an answer besides y when prompted to continue. Putting that together, gives a simplified

Scanner sc = new Scanner(System.in);
while (true) {
    System.out.println("Enter a binary number: ");
    String binaryString = sc.nextLine();
    // An int value consists of up to 32 0 and 1s.
    if (!binaryString.matches("[01]+") || binaryString.length() > 32) {
        continue;
    }
    int v = 0;
    for (int i = 0; i < binaryString.length(); i++) {
        v *= 2;
        if (binaryString.charAt(i) == '1') {
            v++;
        }
    }
    System.out.println("The decimal number is: " + v);

    System.out.println("Continue using the calculator? Only input Y or N");
    String ln = sc.nextLine();
    if (!ln.equalsIgnoreCase("Y")) {
        break;
    }
}

看起来你错过了你错过了我使用的默认值为 2 的基数。试试这个,让我知道会发生什么

i = Integer.parseInt(binaryString,2); 

There may be a nicer way of doing this, however this is the solution that I came up with. I took into account that the number can both be a positive and negative number and added checks for those cases. I also made sure to add exceptions for when an invalid binary number is entered.

    public static int numberFromBinary(String binaryNumber) {

        char[] array = binaryNumber.toCharArray();
        boolean isNegative = false;
        int result = 0;

        if (array.length > 32) {
            throw new NumberFormatException("An integer cannot be more than 32 bits long.");
        }

        if (array.length == 32) {
            isNegative = array[0] == '1';
            if (isNegative) {
                result -= 1;
            }
        }

        for (int i = 0; i < array.length && i != 31; i++) {
            int worth = (int) Math.pow(2, i);
            
            if (array[array.length - 1] != '1' && array[array.length - 1] != '0') {
                throw new NumberFormatException("Binary bits can only be a '1' or a '0'.");
            }
            
            if (isNegative) {
                if (array[array.length - 1] == '0') {
                    result -= worth;
                }
            } else {
                if (array[array.length - 1] == '1') {
                    result += worth;
                }
            }
        }
        return result;
    }

Here's a solution for converting a string representation of a binary number to a decimal number, without using Integer.parseInt(). This is based on your original question text:

How would I be able to use a different method for calculating binary to decimal and implement it into my code?

And also a comment you added:

Also i did not want to use parseint


If you take a binary number and work your way from right to left, each digit is an increasing power of 2.

0001 = 2^0 = 1
0010 = 2^1 = 2
0100 = 2^2 = 4
1000 = 2^3 = 8

You can follow this same pattern: inspect each character position of a binary string input, and raise 2 to some power to get the decimal value represented by that bit being set to 1. Here's a simple bit of code that:

  • prompts for user input as a binary string
  • starting from right and working toward the left, it checks each character, comparing against '1'
  • if the character is in fact 1: take note of the position, raise 2 to the next power, and add that to the running total

Here's the code:

System.out.print("enter a binary number: ");
String binaryInput = new Scanner(System.in).next();
int decimalResult = 0;
int position = 0;

for (int i = binaryInput.length() - 1; i >= 0; i--) {
    if (binaryInput.charAt(i) == '1') {
        decimalResult += Math.pow(2, position);
    }
    position++;
}
System.out.println(binaryInput + " --> " + decimalResult);

And a few sample runs:

enter a binary number: 1111
1111 --> 15

enter a binary number: 101010101
101010101 --> 341

enter a binary number: 100000000000
100000000000 --> 2048

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM