parent
045c7e254a
commit
7507aea561
@ -0,0 +1,75 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
public class BaseConverter {
|
||||
|
||||
// 将任意进制数转换为十进制数
|
||||
public static long convertToDecimal(String number, int base) {
|
||||
long decimal = 0;
|
||||
int length = number.length();
|
||||
|
||||
for (int i = 0; i < length; i++) {
|
||||
char digit = number.charAt(length - 1 - i);
|
||||
int value;
|
||||
|
||||
if (digit >= '0' && digit <= '9') {
|
||||
value = digit - '0';
|
||||
} else if (digit >= 'A' && digit <= 'F') {
|
||||
value = digit - 'A' + 10;
|
||||
} else if (digit >= 'a' && digit <= 'f') {
|
||||
value = digit - 'a' + 10;
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid character in number: " + digit);
|
||||
}
|
||||
|
||||
decimal += value * Math.pow(base, i);
|
||||
}
|
||||
|
||||
return decimal;
|
||||
}
|
||||
|
||||
// 将十进制数转换为任意进制数
|
||||
public static String convertToBase(long decimal, int base) {
|
||||
if (base < 2 || base > 16) {
|
||||
throw new IllegalArgumentException("Base must be between 2 and 16");
|
||||
}
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
char[] digits = "0123456789ABCDEF".toCharArray();
|
||||
|
||||
while (decimal > 0) {
|
||||
int remainder = (int) (decimal % base);
|
||||
result.insert(0, digits[remainder]);
|
||||
decimal /= base;
|
||||
}
|
||||
|
||||
if (result.length() == 0) {
|
||||
result.append('0');
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter the number X: ");
|
||||
String numberX = scanner.nextLine();
|
||||
|
||||
System.out.print("Enter the base of X (2-16): ");
|
||||
int baseX = scanner.nextInt();
|
||||
|
||||
System.out.print("Enter the desired base Y (2-16): ");
|
||||
int baseY = scanner.nextInt();
|
||||
|
||||
try {
|
||||
long decimal = convertToDecimal(numberX, baseX);
|
||||
String numberY = convertToBase(decimal, baseY);
|
||||
|
||||
System.out.println("The number " + numberX + " in base " + baseX + " is " + numberY + " in base " + baseY);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error: " + e.getMessage());
|
||||
}
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
}
|
Loading…
Reference in new issue