我的二进制到十进制转换器的整数大小限制有问题,不确定如何正确实现 long
Having an issue with integer size limitations for my binary to decimal converter, not sure how to implement long properly
我写了一个应用程序,可以将十进制转换为二进制、八进制、十六进制,反之亦然。我最初使用整数 (int) 编写它,虽然它工作得很好,但在数字达到一定大小后它停止工作。所以我环顾四周,看到为了通过这个我必须使用很长时间。我将我的十进制转换为二进制可以正常工作,但是我将二进制转换回十进制的方法在一定长度后仍然无法正常工作。任何帮助将不胜感激
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
。对于采用 long
的方法来说,这是非常出乎意料的。
- 此方法可以处理的最大值是
1111111111111111111L
这样会好很多:
getDecimal(String binaryNum)
请注意,参数名称会提示读取器需要什么样的值。
通过此更改,该方法将能够处理更大的输入,最多 11111111111111111111111111111111111111111111111111111111111111
,也称为 Long.MAX_VALUE
。
除此之外,该方法似乎工作正常。
我写了一个应用程序,可以将十进制转换为二进制、八进制、十六进制,反之亦然。我最初使用整数 (int) 编写它,虽然它工作得很好,但在数字达到一定大小后它停止工作。所以我环顾四周,看到为了通过这个我必须使用很长时间。我将我的十进制转换为二进制可以正常工作,但是我将二进制转换回十进制的方法在一定长度后仍然无法正常工作。任何帮助将不胜感激
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
。对于采用long
的方法来说,这是非常出乎意料的。 - 此方法可以处理的最大值是
1111111111111111111L
这样会好很多:
getDecimal(String binaryNum)
请注意,参数名称会提示读取器需要什么样的值。
通过此更改,该方法将能够处理更大的输入,最多 11111111111111111111111111111111111111111111111111111111111111
,也称为 Long.MAX_VALUE
。
除此之外,该方法似乎工作正常。