|
|
@ -1,70 +1,13 @@
|
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public class jinzhi {
|
|
|
|
public class jinzhi {
|
|
|
|
|
|
|
|
|
|
|
|
// 将数字从 'fromBase' 转换为 'toBase'
|
|
|
|
|
|
|
|
public static String convertBase(String number, int fromBase, int toBase) {
|
|
|
|
|
|
|
|
// 第一步:从 'fromBase' 转换为十进制(base 10)
|
|
|
|
|
|
|
|
int decimalNumber = 0;
|
|
|
|
|
|
|
|
int length = number.length();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 将输入数字转换为十进制
|
|
|
|
|
|
|
|
for (int i = 0; i < length; i++) {
|
|
|
|
|
|
|
|
char digit = number.charAt(length - 1 - i);
|
|
|
|
|
|
|
|
int value;
|
|
|
|
|
|
|
|
if (Character.isDigit(digit)) {
|
|
|
|
|
|
|
|
value = digit - '0'; // 将字符转换为 0-9 的整数
|
|
|
|
|
|
|
|
} else {
|
|
|
|
|
|
|
|
value = Character.toUpperCase(digit) - 'A' + 10; // 将字符转换为 A-F 的整数
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
decimalNumber += value * Math.pow(fromBase, i);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 第二步:从十进制转换为目标进制
|
|
|
|
|
|
|
|
if (decimalNumber == 0) {
|
|
|
|
|
|
|
|
return "0"; // 如果数字为零,返回 "0"
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
StringBuilder result = new StringBuilder();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 将十进制数字转换为目标基数
|
|
|
|
|
|
|
|
while (decimalNumber > 0) {
|
|
|
|
|
|
|
|
int remainder = decimalNumber % toBase;
|
|
|
|
|
|
|
|
if (remainder < 10) {
|
|
|
|
|
|
|
|
result.append((char) (remainder + '0')); // 添加 0-9 的数字
|
|
|
|
|
|
|
|
} else {
|
|
|
|
|
|
|
|
result.append((char) (remainder - 10 + 'A')); // 添加 A-F 的字母
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
decimalNumber /= toBase;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 反转结果,因为我们是从后向前构建的
|
|
|
|
|
|
|
|
return result.reverse().toString();
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Scanner scanner = new Scanner(System.in);
|
|
|
|
int a = 15;
|
|
|
|
|
|
|
|
int x = 0;
|
|
|
|
// 输入数字和基数
|
|
|
|
int i=0;
|
|
|
|
System.out.print("请输入数字: ");
|
|
|
|
while (a > 0) {
|
|
|
|
String number = scanner.nextLine();
|
|
|
|
x = (int) (x + (a % 2) * Math.pow(10,i));
|
|
|
|
|
|
|
|
a = a / 2;
|
|
|
|
System.out.print("请输入原始进制 (2 到 16): ");
|
|
|
|
i=i+1;
|
|
|
|
int fromBase = scanner.nextInt();
|
|
|
|
}
|
|
|
|
|
|
|
|
System.out.print("jinzhi11111十进制a转换二进制x为:" + x);
|
|
|
|
System.out.print("请输入目标进制 (2 到 16): ");
|
|
|
|
|
|
|
|
int toBase = scanner.nextInt();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 验证基数
|
|
|
|
|
|
|
|
if (fromBase < 2 || fromBase > 16 || toBase < 2 || toBase > 16) {
|
|
|
|
|
|
|
|
System.out.println("基数必须在 2 到 16 之间。");
|
|
|
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 转换数字并打印结果
|
|
|
|
|
|
|
|
String result = convertBase(number, fromBase, toBase);
|
|
|
|
|
|
|
|
System.out.println("进制为 " + fromBase + " 的数: " + number + " 在进制为 " + toBase + " 的数是: " + result );
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scanner.close();
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|