You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.5 KiB

4 months ago
import java.util.Scanner;
public class BaseConverter {
// 字符数组用于表示大于9的数字
private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
*
*
* @param str
* @param base
* @return
*/
public static int toDecimal(String str, int base) {
int result = 0;
int power = 0;
for (int i = str.length() - 1; i >= 0; i--) {
char c = str.charAt(i);
int digit = Character.isDigit(c) ? c - '0' : c - 'A' + 10;
result += digit * Math.pow(base, power++);
}
return result;
}
/**
*
*
* @param decimal
* @param targetBase
* @return
*/
public static String fromDecimal(int decimal, int targetBase) {
if (decimal == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
while (decimal > 0) {
result.insert(0, DIGITS[decimal % targetBase]);
decimal /= targetBase;
}
return result.toString();
}
/**
*
*
* @param str
* @param sourceBase
* @param targetBase
* @return
*/
public static String convertBase(String str, int sourceBase, int targetBase) {
int decimalValue = toDecimal(str, sourceBase);
return fromDecimal(decimalValue, targetBase);
}
/**
*
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 获取用户输入
System.out.print("请输入数据(例如 A1: ");
String input = scanner.nextLine().toUpperCase();
System.out.print("请输入源进制数(例如 16: ");
int sourceBase = scanner.nextInt();
System.out.print("请输入目标进制数(例如 2: ");
int targetBase = scanner.nextInt();
// 进制转换
String result = convertBase(input, sourceBase, targetBase);
System.out.println("转换结果:" + result); // 输出转换结果
scanner.close();
}
4 months ago
}