Java 我的二进制到十进制转换器存在整数大小限制问题,不确定如何正确实现long
我写了一个应用程序,可以将十进制转换为二进制、八进制、十六进制,反之亦然。我最初是用整数(int)编写的,尽管它工作得很好,但当数字达到一定大小后,它就停止工作了。所以我环顾四周,发现为了通过考试,我得用很长的时间。我让我的十进制转换成二进制运行良好,但我将二进制转换成十进制的方法在超过一定长度后仍然不起作用。任何帮助都将不胜感激Java 我的二进制到十进制转换器存在整数大小限制问题,不确定如何正确实现long,java,integer,long-integer,Java,Integer,Long Integer,我写了一个应用程序,可以将十进制转换为二进制、八进制、十六进制,反之亦然。我最初是用整数(int)编写的,尽管它工作得很好,但当数字达到一定大小后,它就停止工作了。所以我环顾四周,发现为了通过考试,我得用很长的时间。我让我的十进制转换成二进制运行良好,但我将二进制转换成十进制的方法在超过一定长度后仍然不起作用。任何帮助都将不胜感激 public static long getDecimal(long input) { // Converts the input integer to a Str
public static long getDecimal(long input) {
// Converts the input integer to a String, so we can use charAt and multiply the 1's and 0's by their corresponding power
String inputString = Long.toString(input);
// Decimal is our final decimal output, i our itterator, mult our power and num is a temporary place holder
long decimal = 0;
int i = (inputString.length() - 1);
long mult = 1;
long num = 0;
// As long as our itterator isn't below 0
while (i >= 0) {
// Num, the placeholder, is the value of the character at the index of our itterator, multuplied by our power
num = (Character.getNumericValue(inputString.charAt(i)) * mult);
// Add this our final number
decimal = decimal + num;
// Multiply our power by 2 to get the next one
mult = mult * 2;
// Decrease our itterator by 1
i--;
}
return decimal;
}
我建议将
getDecimal(long input)
方法更改为使用String
而不是long
,原因有二:
- 该方法希望参数看起来像二进制值,例如
。对于采用10010011
的方法来说,这是非常意外的李>长
- 此方法可以处理的最大值是
1111111 l
getDecimal(String binaryNum)
请注意,参数名提示读取它所期望的值类型
通过此更改,该方法将能够处理更大的输入,最多为11111111111111111111111111111111111
,也称为Long.MAX_值
除此之外,该方法似乎工作正常