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.
test/BaseConverter.java

91 lines
2.7 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.

package com.example.baseconverter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class BaseConverter {
// 字符到数值的映射
private static final Map<Character, Integer> charToValueMap = new HashMap<>();
// 数值到字符的映射
private static final Map<Integer, Character> valueToCharMap = new HashMap<>();
static {
// 初始化字符到数值的映射
for (char c = '0'; c <= '9'; c++) {
charToValueMap.put(c, c - '0');
}
for (char c = 'A'; c <= 'F'; c++) {
charToValueMap.put(c, c - 'A' + 10);
}
// 初始化数值到字符的映射
for (int i = 0; i <= 9; i++) {
valueToCharMap.put(i, (char) ('0' + i));
}
for (int i = 10; i <= 15; i++) {
valueToCharMap.put(i, (char) ('A' + i - 10));
}
}
// 将任意进制的数转换为十进制
public static int toDecimal(String number, int base) {
int decimalValue = 0;
int power = 0;
for (int i = number.length() - 1; i >= 0; i--) {
char digit = number.charAt(i);
int value = charToValueMap.get(digit);
decimalValue += value * Math.pow(base, power);
power++;
}
return decimalValue;
}
// 将十进制数转换为任意进制
public static String fromDecimal(int decimalValue, int base) {
if (decimalValue == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
while (decimalValue > 0) {
int remainder = decimalValue % base;
result.insert(0, valueToCharMap.get(remainder));
decimalValue /= base;
}
return result.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入原始进制和数
System.out.print("请输入原始进制 (2-16): ");
int sourceBase = scanner.nextInt();
System.out.print("请输入原始数: ");
String sourceNumber = scanner.next();
// 输入目标进制
System.out.print("请输入目标进制 (2-16): ");
int targetBase = scanner.nextInt();
// 验证输入
if (sourceBase < 2 || sourceBase > 16 || targetBase < 2 || targetBase > 16) {
System.out.println("进制必须在2到16之间");
return;
}
// 转换
int decimalValue = toDecimal(sourceNumber, sourceBase);
String targetNumber = fromDecimal(decimalValue, targetBase);
// 输出结果
System.out.println("转换后的数是: " + targetNumber);
}
}