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.
34 lines
1.0 KiB
34 lines
1.0 KiB
1 month ago
|
document.getElementById('convert').addEventListener('click', function () {
|
||
|
const input = document.getElementById('input').value;
|
||
|
const fromBase = parseInt(document.getElementById('from-base').value);
|
||
|
const toBase = parseInt(document.getElementById('to-base').value);
|
||
|
|
||
|
// 将输入转换为十进制
|
||
|
let decimal;
|
||
|
try {
|
||
|
decimal = parseInt(input, fromBase);
|
||
|
if (isNaN(decimal)) throw new Error("无效输入");
|
||
|
} catch (error) {
|
||
|
document.getElementById('result').innerText = "输入无效,请检查!";
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// 将十进制转换为目标进制
|
||
|
let result;
|
||
|
switch (toBase) {
|
||
|
case 2:
|
||
|
result = decimal.toString(2);
|
||
|
break;
|
||
|
case 8:
|
||
|
result = decimal.toString(8);
|
||
|
break;
|
||
|
case 10:
|
||
|
result = decimal.toString(10);
|
||
|
break;
|
||
|
case 16:
|
||
|
result = decimal.toString(16).toUpperCase();
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
document.getElementById('result').innerText = result;
|
||
|
});
|