简体   繁体   English

(java) 不使用 parseint 将十进制数转换为二进制数

[英](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.我是java新手,我正在学习如何从二进制转换为十进制,反之亦然。 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.在二进制转十进制的情况下,我发现我可以使用 parseint,但是我看到了其他没有使用它的方法,所以我尝试将它们实现到我的代码中,但它对我不起作用,我得到了难住了。

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.二进制数学涉及加 1 和乘以 2。我会使用正则表达式来测试输入是否有效。 I would use an infinite loop and break when the user gives an answer besides y when prompted to continue.当用户在提示继续时给出除y之外的答案时,我会使用无限循环并中断。 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().这是将二进制数的字符串表示形式转换为十进制数的解决方案,无需使用 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我也不想使用 parseint


If you take a binary number and work your way from right to left, each digit is an increasing power of 2.如果你取一个二进制数并从右到左计算,每个数字都是 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:您可以遵循相同的模式:检查二进制字符串输入的每个字符位置,然后将 2 提高到某个幂,以获得该位表示的十进制值被设置为 1。下面是一段简单的代码:

  • prompts for user input as a binary string提示用户输入为二进制字符串
  • starting from right and working toward the left, it checks each character, comparing against '1'从右开始向左工作,它检查每个字符,与'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如果角色实际上是 1:记下位置,将 2 提高到下一个幂,并将其添加到运行总数中

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 不使用 parseint 或 arrays 的二进制到十进制转换器 - binary to decimal converter without using parseint or arrays 不使用数组将十进制数转换为二进制数 - Convert Decimal Number to Binary without using Array 十进制输入然后二进制输入(不使用 Integer.parseInt) - Decimal input then Binary input (without using Integer.parseInt) 在不依赖parseInt的情况下,使用Java以任意位数将一个二进制输入拼接为另一个二进制输入的有效方法是什么? - What is an efficient way to splice one binary input into another at an arbitrary bit number using Java without relying on parseInt? 即使在Java中使用parseInt,也无法将二进制字符串转换为整数 - Unable to convert binary string to integer despite using parseInt in java 使用创建的常量(不是parseINT())将二进制更改为十进制,并声明和初始化数字的8位中的每一个 - Changing binary to decimal using created constants (not parseINT() ) and declaring and initializing each of the 8 bits of the number 不使用内置函数(例如parseInt,Math.pow)等,从十进制转换为二进制 - Decimal to Binary without using in-built functions (like parseInt, Math.pow), etc 如何编写一个不使用lang类将二进制数转换为十进制数的程序? - how to write a program to convert a binary number to decimal number without using lang class? 如何使用模数在Java中将二进制转换为十进制? - How to convert binary to decimal in java using modulus? 使用递归将十进制转换为二进制 Java - Convert Decimal to Binary using Recursion Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM