简体   繁体   English

在Java中读取长二进制数

[英]Reading long binary numbers in java

110011000111100111001100011110011100110001111001110011000111100111001100011110011100110001111001

That's not a valid way to check a binary number. 这不是检查二进制数的有效方法。 You're converting to an int in base 10, then checking that each of the digits in base 10 is zero or one. 您要转换为以10为底的int ,然后检查以10为底的每个数字是否为零或一。 The conversion itself will fail on long enough input strings, and if it doesn't the checking will fail as well. 转换本身将在足够长的输入字符串上失败,否则,检查也将失败。

You shouldn't be converting it all all, you should be checking the input string itself. 您不应该全部转换,应该检查输入字符串本身。

EDIT Actually you don't have to do anything. 编辑实际上,您无需执行任何操作。 Integer.parseInt() will check it for you and throw NumberFormatException if the string isn't a number in the specified radix. 如果字符串不是指定基数中的数字,则Integer.parseInt()将为您检查它并引发NumberFormatException

You are parsing your binary digit string as a decimal integer first. 您首先将二进制数字字符串解析为十进制整数。 If it has more than 10 significant digits then its decimal interpretation is too big to fit in an int , so the decimal conversion fails. 如果它的有效位数超过10个,则其十进制解释太大而无法容纳int ,因此十进制转换失败。

When you are going to parse the digit string as a binary number, simply avoid first parsing it as a decimal one. 当您要将数字字符串解析为二进制数时,只需避免先将其解析为十进制数即可。 For instance, most of what you posted could be reduced to this: 例如,您发布的大部分内容都可以简化为:

int inputNumber = Integer.parseInt(returnEnterNumber(), 
        binaryToDecimal.isSelected() ? 2 : 10);

Take a look at Integers MAX values: 看一看Integers MAX值:

public class MainClass {

public static void main(String[] arg) {
System.out.println(Integer.MAX_VALUE);   

System.out.println(Integer.MIN_VALUE);   

 }
}

the output will be: 输出将是:

2147483647
-2147483648

This means that if you have more than 10 digits, you have exceeded the max number for the Integer data type. 这意味着,如果您的位数超过10位,则超出了Integer数据类型的最大数量。 Try Using BigInteger on your binary value or consider returning it as String 尝试对您的二进制值使用BigInteger或考虑将其作为String返回

这是一行代码,可以满足您的需求

System.out.println(new BigInteger("10101010101010111101010101001101010101010101001010101010101001011101010101010101",2).toString());

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

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