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.
jzzh/jzzh.html

68 lines
2.2 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.

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>进制转换</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
max-width: 400px;
}
label, input, button {
display: block;
margin-bottom: 10px;
}
#result {
font-weight: bold;
}
</style>
</head>
<body>
<h2>任意进制转换器</h2>
<label for="fromBase">输入进制 (2-16):</label>
<input type="number" id="fromBase" min="2" max="16" required>
<label for="number">输入数字:</label>
<input type="text" id="number" placeholder="例如1010" required>
<label for="toBase">转换为进制 (2-16):</label>
<input type="number" id="toBase" min="2" max="16" required>
<button id="convertButton">转换</button>
<h3>结果:</h3>
<div id="result"></div>
<script>
document.getElementById('convertButton').addEventListener('click', () => {
const fromBase = parseInt(document.getElementById('fromBase').value);
const number = document.getElementById('number').value.trim();
const toBase = parseInt(document.getElementById('toBase').value);
// 验证输入的数字是否合法
if (!/^[0-9A-Fa-f]+$/.test(number) || !isValidForBase(number, fromBase)) {
document.getElementById('result').textContent = '输入的数字不符合指定的进制规则!';
return;
}
// 转换为十进制
const decimalValue = parseInt(number, fromBase);
const convertedValue = decimalValue.toString(toBase).toUpperCase();
// 显示结果
document.getElementById('result').textContent = convertedValue;
});
function isValidForBase(numStr, base) {
const validChars = '0123456789ABCDEF'.slice(0, base);
return [...numStr].every(char => validChars.includes(char.toUpperCase()));
}
</script>
</body>
</html>