简体   繁体   English

如何将大二进制转换为十进制?

[英]How to convert large binary to decimal?

It works when I enter binary like 10, 1011, 1101. But it always prints "Not binary" when I enter 10011010010, whereas it should be 1234. How to modify it? 当我输入二进制代码(例如10、1011、1101)时,它可以工作。但是,当我输入10011010010时,它始终显示“ Not binary”,而应该是1234。如何进行修改?

import java.util.Scanner;
public class Binary {

    public static int toDecimal(String b) {     
        int decimal = Integer.parseInt(b,2);
        return decimal;
    }


    public static boolean isBinary(String b) {
        int inputNum = Integer.parseInt(b);

        while(inputNum != 0){
            if(inputNum % 10 > 1){
                return false;
            }
            inputNum = inputNum / 10;
        }
        return true;
    }

    public static void main(String[] args) {

        System.out.print("Enter binary: ");
        Scanner in = new Scanner(System.in);
        String binaryNum = in.next();

        try{
            int intNum = Integer.parseInt(binaryNum);

            boolean isBinary = isBinary(binaryNum);
            if(isBinary){
                int outputDecimal = toDecimal(binaryNum);
                System.out.println("\n"+ outputDecimal +" in decimal");
            }else{
                System.out.println("\n" + "Not binary!");
            }
        }catch(Exception e){
            System.out.println("\n" + "Not binary!");
        }
    }
}

Why so many conversions from string to int? 为什么要这么多从string到int的转换? Keep the input in string form for checking if the input is binary or not. 使输入保持字符串形式,以检查输入是否为二进制。 Then finally convert the string to number type. 然后最后将字符串转换为数字类型。 If you think your input will not exceed the maximum int value, you can use parseInt() otherwise use either long or BigInteger . 如果您认为您的输入不会超过最大int值,则可以使用parseInt()否则可以使用longBigInteger

With input as string, your isBinary() may look like this: 使用输入作为字符串,您的isBinary()可能如下所示:

public static boolean isBinary(String b) {
    for(int i=0; i<b.length(); i++) {
        if(b.charAt(i) != '0' && b.charAt(i) != '1') {
            return false;
        }
    }
    return true;
}

Then change all your Integer.parseInt() calls to long.parseLong() , and change the associated variables accordingly, ie from int to long. 然后将所有Integer.parseInt()调用都更改为long.parseLong() ,并相应地更改关联的变量,即从int更改为long。 That should be enough to get what you expect, for now. 到目前为止,这应该足以满足您的期望。 What I mean is for arbitrarily large inputs, you have to use BigInteger (see below). 我的意思是对于任意大的输入,您必须使用BigInteger(请参见下文)。


If you choose to use java.math.BigInteger , you can use the constructor with the radix like so: 如果选择使用java.math.BigInteger ,则可以将构造函数与基数一起使用,如下所示:

public static BigInteger toDecimal(String b) {
    return new BigInteger(b, 2);
}

The problem is that you are trying to parse a number that exceeds 问题是您正在尝试解析一个超出
Integer.MAX_VALUE which is 2^31 - 1 : Integer.MAX_VALUE 为2 ^ Integer.MAX_VALUE

int intNum = Integer.parseInt(binaryNum);

Try using Long.parseLong instead. 尝试改用Long.parseLong A long has 64 bits and has a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 which should be enough to cover your various inputs (although obviously will fail for longer numbers). long有64位,其范围为-9,223,372,036,854,775,8089,223,372,036,854,775,807 ,这足以覆盖您的各种输入(尽管很显然,较长的数字会失败)。

This works although it would be more efficient to process more than 1 bit at a time. 尽管每次处理多于1个位会更有效,但这是可行的。 Result for 1000000000000000000000000000000000000000000000000000000000000000 is 9,223,372,036,854,775,808 1000000000000000000000000000000000000000000000000000000000000000000000的结果是9,223,372,036,854,775,808

import java.util.regex.Pattern;
import java.math.BigDecimal;

...

public static BigDecimal toDecimal(String b) {     
    BigDecimal bd1 = new BigDecimal(b.charAt(0)=='1'?1:0);
    BigDecimal two = new BigDecimal(2);
    for (int i = 1; i<b.length(); i++) {
        bd1 = bd1.multiply(two);
        bd1 = bd1.add(new BigDecimal(b.charAt(i)=='1'?1:0));
    }
    return bd1;
}

public static boolean isBinary(String b) {
    return Pattern.compile("[01]+").matcher(b).matches();
}    

public static void main(String[] args) {
    System.out.print("Enter binary: ");
    Scanner in = new Scanner(System.in);
    String binaryNum = in.next();

    try{
        boolean isBinary = isBinary(binaryNum);
        if(isBinary){
            BigDecimal outputDecimal = toDecimal(binaryNum);
            System.out.println("\n"+ outputDecimal +" in decimal");
        }else{
            System.out.println("\n" + "Not binary!");
        }
    }catch(Exception e){
        System.out.println("\n" + "Not binary!");
    }
}

More minimal version with use of BigInteger 使用BigInteger的最小版本

public static void main(String[] args) {
    System.out.print("Enter binary: ");
    Scanner in = new Scanner(System.in);
    String binaryNum = in.next();

    try{
        if(Pattern.compile("[01]+").matcher(binaryNum).matches()){
            BigInteger outputDecimal = new BigInteger(binaryNum, 2);
            System.out.println("\n"+ outputDecimal +" in decimal");
        }else{
            System.out.println("\n" + "Not binary!");
        }
    }catch(Exception e){
        System.out.println("\n" + "Not binary!");
    }
}

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

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