【源码文件】二进制与十进制转化及计算之计算器网页
二进制与十进制转化及计算之计算器网页,可在无网络情况下使用【源码如下】:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>二进制与十进制计算器(支持负数)</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- 配置Tailwind自定义颜色和字体 -->
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: '#3B82F6',
secondary: '#10B981',
accent: '#8B5CF6',
dark: '#1E293B',
light: '#F8FAFC'
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
},
}
}
}
</script>
<style type="text/tailwindcss">
@layer utilities {
.content-auto {
content-visibility: auto;
}
.transition-all-300 {
transition: all 300ms ease-in-out;
}
.shadow-soft {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
.input-focus {
@apply focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none;
}
}
</style>
</head>
<body class="bg-gradient-to-br from-light to-slate-100 min-h-screen font-sans text-dark">
<!-- 页面容器 -->
<div class="container mx-auto px-4 py-8 max-w-4xl">
<!-- 标题区域 -->
<header class="text-center mb-10">
<h1 class="text- font-bold text-dark mb-2 bg-clip-text text-transparent bg-gradient-to-r from-primary to-accent">
二进制与十进制计算器
</h1>
<p class="text-slate-600 text-lg max-w-2xl mx-auto">
支持负数转换的离线工具,可进行二进制与十进制互转及二进制基本运算
</p>
</header>
<!-- 主内容区域 -->
<main class="bg-white rounded-2xl shadow-soft p-6 md:p-8 mb-10 transform hover:shadow-lg transition-all-300">
<!-- 操作类型选择 -->
<div class="mb-8">
<h2 class="text-xl font-semibold mb-4 text-slate-800">选择操作类型</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<button id="convert-btn" class="operation-btn bg-primary text-white py-3 px-6 rounded-xl font-medium flex items-center justify-center gap-2 active">
<i class="fa fa-exchange"></i>
<span>进制转换</span>
</button>
<button id="calculate-btn" class="operation-btn bg-slate-200 text-slate-700 py-3 px-6 rounded-xl font-medium flex items-center justify-center gap-2">
<i class="fa fa-calculator"></i>
<span>二进制计算</span>
</button>
</div>
</div>
<!-- 进制转换区域 -->
<div id="convert-section" class="operation-section">
<h3 class="text-lg font-semibold mb-4 text-slate-800">进制转换</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
<div>
<label for="decimal-input" class="block text-sm font-medium text-slate-700 mb-1">十进制数字</label>
<div class="relative">
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500">
<i class="fa fa-hashtag"></i>
</span>
<input type="number" id="decimal-input" placeholder="输入十进制数字(可负数)"
class="w-full pl-10 pr-4 py-3 rounded-lg border border-slate-300 input-focus transition-all-300">
</div>
<p class="text-xs text-slate-500 mt-1">例如: 42 或 -42</p>
</div>
<div>
<label for="binary-input" class="block text-sm font-medium text-slate-700 mb-1">二进制数字</label>
<div class="relative">
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500">
<i class="fa fa-code"></i>
</span>
<input type="text" id="binary-input" placeholder="输入二进制数字(可带符号)"
class="w-full pl-10 pr-4 py-3 rounded-lg border border-slate-300 input-focus transition-all-300">
</div>
<p class="text-xs text-slate-500 mt-1">例如: 101010 或 -101010(补码表示)</p>
</div>
</div>
<div class="flex justify-center">
<button id="convert-calculate" class="bg-secondary hover:bg-secondary/90 text-white py-3 px-8 rounded-xl font-medium flex items-center gap-2 transition-all-300">
<i class="fa fa-refresh"></i>
<span>转换</span>
</button>
</div>
</div>
<!-- 二进制计算区域 -->
<div id="calculate-section" class="operation-section hidden">
<h3 class="text-lg font-semibold mb-4 text-slate-800">二进制计算</h3>
<div class="space-y-6 mb-6">
<div>
<label for="binary-num1" class="block text-sm font-medium text-slate-700 mb-1">第一个二进制数字</label>
<div class="relative">
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500">
<i class="fa fa-code"></i>
</span>
<input type="text" id="binary-num1" placeholder="输入二进制数字(可带符号)"
class="w-full pl-10 pr-4 py-3 rounded-lg border border-slate-300 input-focus transition-all-300">
</div>
</div>
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">选择运算符</label>
<div class="grid grid-cols-4 gap-3">
<button class="operator-btn bg-slate-200 hover:bg-slate-300 py-3 rounded-lg font-medium transition-all-300" data-op="+">+</button>
<button class="operator-btn bg-slate-200 hover:bg-slate-300 py-3 rounded-lg font-medium transition-all-300" data-op="-">-</button>
<button class="operator-btn bg-slate-200 hover:bg-slate-300 py-3 rounded-lg font-medium transition-all-300" data-op="*">×</button>
<button class="operator-btn bg-slate-200 hover:bg-slate-300 py-3 rounded-lg font-medium transition-all-300" data-op="/">÷</button>
</div>
</div>
<div>
<label for="binary-num2" class="block text-sm font-medium text-slate-700 mb-1">第二个二进制数字</label>
<div class="relative">
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500">
<i class="fa fa-code"></i>
</span>
<input type="text" id="binary-num2" placeholder="输入二进制数字(可带符号)"
class="w-full pl-10 pr-4 py-3 rounded-lg border border-slate-300 input-focus transition-all-300">
</div>
</div>
</div>
<div class="flex justify-center">
<button id="binary-calculate" class="bg-secondary hover:bg-secondary/90 text-white py-3 px-8 rounded-xl font-medium flex items-center gap-2 transition-all-300">
<i class="fa fa-calculator"></i>
<span>计算结果</span>
</button>
</div>
</div>
<!-- 结果显示区域 -->
<div id="result-section" class="mt-8 hidden">
<div class="border-t border-slate-200 pt-6">
<h3 class="text-lg font-semibold mb-4 text-slate-800">结果</h3>
<div class="bg-slate-50 rounded-xl p-5">
<div id="result-content" class="text-xl font-mono break-all"></div>
<div id="result-details" class="text-sm text-slate-600 mt-2"></div>
</div>
</div>
</div>
</main>
<!-- 注意事项区域 -->
<section class="bg-white/80 backdrop-blur-sm rounded-xl shadow-soft p-6 mb-10">
<h2 class="text-lg font-semibold mb-3 text-slate-800 flex items-center gap-2">
<i class="fa fa-info-circle text-primary"></i>
使用说明与注意事项
</h2>
<ul class="space-y-2 text-slate-700">
<li class="flex items-start gap-2">
<i class="fa fa-check-circle text-secondary mt-1"></i>
<span>支持负数转换:十进制可直接输入负号,二进制负数需以负号开头(补码表示)</span>
</li>
<li class="flex items-start gap-2">
<i class="fa fa-check-circle text-secondary mt-1"></i>
<span>选择需要的操作类型(转换或计算),输入相应的数字,点击按钮获取结果</span>
</li>
<li class="flex items-start gap-2">
<i class="fa fa-exclamation-circle text-amber-500 mt-1"></i>
<span>二进制数主体只能包含0和1,输入其他字符将导致错误</span>
</li>
<li class="flex items-start gap-2">
<i class="fa fa-exclamation-circle text-amber-500 mt-1"></i>
<span>除法操作结果必须是整数,否则将提示错误</span>
</li>
<li class="flex items-start gap-2">
<i class="fa fa-wifi text-slate-500 mt-1"></i>
<span>本工具可在无网络环境下使用,刷新页面即可重新开始</span>
</li>
</ul>
</section>
<!-- 页脚 -->
<footer class="text-center text-slate-500 text-sm py-4">
<p>二进制与十进制计算器 © 2023 - 支持负数转换的离线工具</p>
</footer>
</div>
<!-- 错误提示模态框 -->
<div id="error-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
<div class="bg-white rounded-xl p-6 max-w-md w-full mx-4 transform transition-all-300 scale-95 opacity-0" id="modal-content">
<div class="text-center">
<div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
<i class="fa fa-times text-2xl text-red-500"></i>
</div>
<h3 class="text-xl font-semibold text-slate-800 mb-2">输入错误</h3>
<p id="error-message" class="text-slate-600 mb-6"></p>
<button id="close-modal" class="bg-primary hover:bg-primary/90 text-white py-2 px-6 rounded-lg font-medium transition-all-300">
确定
</button>
</div>
</div>
</div>
<script>
// DOM元素
const convertBtn = document.getElementById('convert-btn');
const calculateBtn = document.getElementById('calculate-btn');
const convertSection = document.getElementById('convert-section');
const calculateSection = document.getElementById('calculate-section');
const operatorBtns = document.querySelectorAll('.operator-btn');
const resultSection = document.getElementById('result-section');
const resultContent = document.getElementById('result-content');
const resultDetails = document.getElementById('result-details');
const errorModal = document.getElementById('error-modal');
const modalContent = document.getElementById('modal-content');
const errorMessage = document.getElementById('error-message');
const closeModal = document.getElementById('close-modal');
// 当前选中的运算符
let selectedOperator = '+';
// 初始化事件监听
function initEventListeners() {
// 操作类型切换
convertBtn.addEventListener('click', () => switchOperation('convert'));
calculateBtn.addEventListener('click', () => switchOperation('calculate'));
// 运算符选择
operatorBtns.forEach(btn => {
btn.addEventListener('click', () => {
operatorBtns.forEach(b => {
b.classList.remove('bg-primary', 'text-white');
b.classList.add('bg-slate-200', 'text-slate-700');
});
btn.classList.remove('bg-slate-200', 'text-slate-700');
btn.classList.add('bg-primary', 'text-white');
selectedOperator = btn.dataset.op;
});
});
// 默认选中加号
operatorBtns.click();
// 转换按钮
document.getElementById('convert-calculate').addEventListener('click', handleConversion);
// 计算按钮
document.getElementById('binary-calculate').addEventListener('click', handleCalculation);
// 关闭错误模态框
closeModal.addEventListener('click', closeErrorModal);
// 输入事件 - 二进制输入仅允许0和1,可包含前导负号
document.getElementById('binary-input').addEventListener('input', (e) => {
// 保留负号(只能有一个且在开头),其余只能是0和1
let value = e.target.value;
if (value.startsWith('-')) {
// 处理负数情况
const rest = value.slice(1).replace(/[^01]/g, '');
e.target.value = '-' + rest;
} else {
// 处理正数情况
e.target.value = value.replace(/[^01]/g, '');
}
});
document.getElementById('binary-num1').addEventListener('input', (e) => {
let value = e.target.value;
if (value.startsWith('-')) {
const rest = value.slice(1).replace(/[^01]/g, '');
e.target.value = '-' + rest;
} else {
e.target.value = value.replace(/[^01]/g, '');
}
});
document.getElementById('binary-num2').addEventListener('input', (e) => {
let value = e.target.value;
if (value.startsWith('-')) {
const rest = value.slice(1).replace(/[^01]/g, '');
e.target.value = '-' + rest;
} else {
e.target.value = value.replace(/[^01]/g, '');
}
});
// 十进制输入变化时自动清除二进制输入
document.getElementById('decimal-input').addEventListener('input', (e) => {
if (e.target.value) {
document.getElementById('binary-input').value = '';
}
});
// 二进制输入变化时自动清除十进制输入
document.getElementById('binary-input').addEventListener('input', (e) => {
if (e.target.value) {
document.getElementById('decimal-input').value = '';
}
});
}
// 切换操作类型
function switchOperation(type) {
if (type === 'convert') {
// 激活转换模式
convertBtn.classList.remove('bg-slate-200', 'text-slate-700');
convertBtn.classList.add('bg-primary', 'text-white');
calculateBtn.classList.remove('bg-primary', 'text-white');
calculateBtn.classList.add('bg-slate-200', 'text-slate-700');
convertSection.classList.remove('hidden');
calculateSection.classList.add('hidden');
} else {
// 激活计算模式
calculateBtn.classList.remove('bg-slate-200', 'text-slate-700');
calculateBtn.classList.add('bg-primary', 'text-white');
convertBtn.classList.remove('bg-primary', 'text-white');
convertBtn.classList.add('bg-slate-200', 'text-slate-700');
calculateSection.classList.remove('hidden');
convertSection.classList.add('hidden');
}
// 隐藏结果区域
resultSection.classList.add('hidden');
}
// 显示错误信息
function showError(message) {
errorMessage.textContent = message;
errorModal.classList.remove('hidden');
// 触发动画
setTimeout(() => {
modalContent.classList.remove('scale-95', 'opacity-0');
modalContent.classList.add('scale-100', 'opacity-100');
}, 10);
}
// 关闭错误模态框
function closeErrorModal() {
modalContent.classList.remove('scale-100', 'opacity-100');
modalContent.classList.add('scale-95', 'opacity-0');
setTimeout(() => {
errorModal.classList.add('hidden');
}, 300);
}
// 验证二进制数(支持负数)
function isValidBinary(binary) {
if (binary.length === 0) return false;
// 允许以负号开头,后面只能是0和1,且至少有一个数字
return /^-?+$/.test(binary) && binary.replace(/-/, '').length > 0;
}
// 十进制转二进制(支持负数,使用补码表示)
function decimalToBinary(decimal) {
if (decimal === 0) return '0';
const isNegative = decimal < 0;
const absValue = Math.abs(decimal);
// 转换为正数的二进制
let binary = absValue.toString(2);
// 如果是负数,计算补码
if (isNegative) {
// 为了简化,我们在前面添加负号表示补码形式
return '-' + binary;
}
return binary;
}
// 二进制转十进制(支持负数)
function binaryToDecimal(binary) {
const isNegative = binary.startsWith('-');
const binaryDigits = isNegative ? binary.slice(1) : binary;
// 转换为十进制
const absValue = parseInt(binaryDigits, 2);
return isNegative ? -absValue : absValue;
}
// 处理转换
function handleConversion() {
const decimalInput = document.getElementById('decimal-input').value.trim();
const binaryInput = document.getElementById('binary-input').value.trim();
// 验证输入
if (decimalInput && binaryInput) {
showError('请只输入一个数字(十进制或二进制)进行转换');
return;
}
if (!decimalInput && !binaryInput) {
showError('请输入一个十进制或二进制数字');
return;
}
let result, details;
if (decimalInput) {
// 十进制转二进制
const decimal = parseInt(decimalInput, 10);
if (isNaN(decimal)) {
showError('请输入有效的十进制数字');
return;
}
result = decimalToBinary(decimal);
details = `${decimal} (十进制) = ${result} (二进制,补码表示)`;
} else {
// 二进制转十进制
if (!isValidBinary(binaryInput)) {
showError('请输入有效的二进制数字(仅包含0和1,可带负号)');
return;
}
const decimal = binaryToDecimal(binaryInput);
result = decimal.toString();
details = `${binaryInput} (二进制,补码表示) = ${decimal} (十进制)`;
}
// 显示结果
displayResult(result, details);
}
// 处理二进制计算
function handleCalculation() {
const num1 = document.getElementById('binary-num1').value.trim();
const num2 = document.getElementById('binary-num2').value.trim();
// 验证输入
if (!num1 || !num2) {
showError('请输入两个二进制数字');
return;
}
if (!isValidBinary(num1) || !isValidBinary(num2)) {
showError('请输入有效的二进制数字(仅包含0和1,可带负号)');
return;
}
// 转换为十进制进行计算
const decimal1 = binaryToDecimal(num1);
const decimal2 = binaryToDecimal(num2);
let decimalResult;
let operationSign;
switch (selectedOperator) {
case '+':
decimalResult = decimal1 + decimal2;
operationSign = '+';
break;
case '-':
decimalResult = decimal1 - decimal2;
operationSign = '-';
break;
case '*':
decimalResult = decimal1 * decimal2;
operationSign = '×';
break;
case '/':
if (decimal2 === 0) {
showError('除数不能为0');
return;
}
if (decimal1 % decimal2 !== 0) {
showError('除法结果必须是整数');
return;
}
decimalResult = decimal1 / decimal2;
operationSign = '÷';
break;
default:
showError('未知的运算符');
return;
}
// 转换回二进制
const binaryResult = decimalToBinary(decimalResult);
// 构建详细信息
const details = `${num1} (二进制) ${operationSign} ${num2} (二进制) = ${binaryResult} (二进制)<br>
${decimal1} (十进制) ${operationSign} ${decimal2} (十进制) = ${decimalResult} (十进制)`;
// 显示结果
displayResult(binaryResult, details);
}
// 显示结果
function displayResult(result, details) {
resultContent.textContent = result;
resultDetails.innerHTML = details;
// 显示结果区域并添加动画
resultSection.classList.remove('hidden');
resultSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
// 添加淡入动画
resultSection.style.opacity = '0';
resultSection.style.transform = 'translateY(10px)';
resultSection.style.transition = 'opacity 300ms ease, transform 300ms ease';
setTimeout(() => {
resultSection.style.opacity = '1';
resultSection.style.transform = 'translateY(0)';
}, 10);
}
// 初始化应用
function initApp() {
initEventListeners();
}
// 启动应用
document.addEventListener('DOMContentLoaded', initApp);
</script>
</body>
</html>
页:
[1]