我写了以下代码:
public String alphabets = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#$%";
public Integer findBase(String input) {
int i = 0;
Integer base = 0;
Integer temp = 0;
while (i != input.length()) {
temp = alphabets.indexOf(input.charAt(i)) + 1;
if (temp > base) {
base = temp;
}
i ++;
}
public String convert(String input, Integer to_base, Integer from_base) {
int i;
Long base_ten = 0L;
Integer input_base = 0;
// If specified, then consider that base as input from base, or else,
// calculate the base of the number
if (from_base == 0) {
input_base = findBase(input);
} else {
input_base = from_base;
}
Integer power = 0;
Double temp_power = 0.0;
while (!input.equals("")) {
temp_power = Math.pow(input_base, power);
base_ten = base_ten + alphabets.indexOf(input.charAt(input.length() - 1)) * temp_power.intValue();
input = input.substring(0, input.length() - 1);
power = power + 1;
}
Long rem = 0L;
String result = "";
while (base_ten != 0L) {
rem = base_ten % to_base;
base_ten = base_ten / to_base;
result = result + alphabets.charAt(rem.intValue());
}
String reverse = new StringBuffer(result).reverse().toString();
return reverse;
}
使用上面的代码,可以将诸如“suchin”(Base 31)之类的字符串转换为其他基础。但是每当我使用更大的东西时,比如说“suchind”,我会在上面代码的下面一行得到一个异常:
result = result + alphabets.charAt(rem.intValue());
说索引是-1。当我更深入地挖掘时,我觉得 rem.intValue() 对于某些大值会以某种方式变为负数 (-1)。不知道如何解决这个问题。有没有办法在java中的大数基数之间进行转换?
BigInteger 版本的代码如下:
public String convert(String input, BigInteger to_base, BigInteger from_base) {
int i;
BigInteger base_ten = new BigInteger("0");
BigInteger input_base = new BigInteger("0");
if (from_base.equals(BigInteger.valueOf(0))) {
input_base = BigInteger.valueOf(findBase(input));
} else {
input_base = from_base;
}
BigInteger power = new BigInteger("0");
BigInteger temp_power = new BigInteger("0");
BigInteger to_add = new BigInteger("0");
while (!input.equals("")) {
temp_power = input_base.pow(power.intValue());
to_add = BigInteger.valueOf(alphabets.indexOf(input.charAt(input.length() - 1)));
to_add = to_add.multiply(temp_power);
base_ten = base_ten.add(to_add);
input = input.substring(0, input.length() - 1);
power = power.add(BigInteger.valueOf(1));
}
BigInteger rem = new BigInteger("0");
String result = "";
while (!base_ten.equals(BigInteger.valueOf(0))) {
rem = base_ten.remainder(to_base);
base_ten = base_ten.divide(to_base);
result = result + alphabets.charAt(rem.intValue());
}
String reverse = new StringBuffer(result).reverse().toString();
return reverse;
}
上面的代码现在可以正常工作了。早些时候我做了以下事情:
while( base_ten != BigInteger.valueOf(0)) {
这导致了无限循环,因为显然这不是在 BigIntegers 中比较的方式:)