我写了以下代码:
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中进行比较的方式:)