在Integer.ParseInt(Number, radix) 可以将2~32进制的数转化为10进制
本代码就是通过将 数值按照当前进制转为10进制,然后转化为2进制
再次通过2进制转换到任意进制的目的
Java类的实现
public class NumberBase {
private int nowNumberBase;
private int targetNumberBase;
private String number;
public String result;
public NumberBase(int nowNumberBase, int targetNumberBase, String number) {
this.nowNumberBase = nowNumberBase;
this.targetNumberBase = targetNumberBase;
this.number = number;
go();
}
private String convertToBinary() {
String binaryNumber = "";
int decimalNumber = Integer.parseInt(number, nowNumberBase);
while (decimalNumber > 0) {
binaryNumber = (decimalNumber % 2) + binaryNumber;
decimalNumber /= 2;
}
return binaryNumber.isEmpty() ? "0" : binaryNumber;
}
private String convertFromBinary(int targetBase) {
String binaryNumber = convertToBinary();
int decimalNumber = Integer.parseInt(binaryNumber, 2);
return Integer.toString(decimalNumber, targetBase);
}
private void go() {
if (nowNumberBase < 2 || number.isEmpty()) {
System.out.println("数值不合法");
return;
}
result = convertFromBinary(targetNumberBase);
}
}
测试类的编写
public class TextNumberBase {
public static void main(String[] args) {
NumberBase test = new NumberBase(10, 30, "175");
String number = test.result;
System.out.println( number );
}
}