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.

58 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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);
}
}