'use strict'; /* ═══════════════════════════════════════════════════════════ Конвертер систем счисления — 10 класс Перевод чисел между системами 2–16 с пошаговым решением ═══════════════════════════════════════════════════════════ */ // Заполняем селекты const fromSelect = document.getElementById('csFromBase'); const toSelect = document.getElementById('csToBase'); for (let b = 2; b <= 16; b++) { const opt1 = new Option(b + '', b); const opt2 = new Option(b + '', b); fromSelect.add(opt1); toSelect.add(opt2); } fromSelect.value = '10'; toSelect.value = '2'; /* ── Утилиты ─────────────────────────────────────────────── */ function digitToChar(d) { if (d < 10) return String(d); return String.fromCharCode(55 + d); } function charToDigit(ch) { const c = ch.toUpperCase(); if (c >= '0' && c <= '9') return c.charCodeAt(0) - 48; if (c >= 'A' && c <= 'F') return c.charCodeAt(0) - 55; return -1; } function toDecimal(numStr, base) { numStr = numStr.trim().toUpperCase(); let result = 0; for (let i = 0; i < numStr.length; i++) { const d = charToDigit(numStr[i]); if (d < 0 || d >= base) return null; result = result * base + d; } return result; } function fromDecimal(decimal, base) { if (decimal === 0) return '0'; let result = ''; while (decimal > 0) { result = digitToChar(decimal % base) + result; decimal = Math.floor(decimal / base); } return result; } function isValidForBase(numStr, base) { numStr = numStr.trim().toUpperCase(); for (let i = 0; i < numStr.length; i++) { const d = charToDigit(numStr[i]); if (d < 0 || d >= base) return false; } return true; } /* ── Пошаговые решения ───────────────────────────────────── */ function stepExpandedForm(numStr, fromBase) { numStr = numStr.trim().toUpperCase(); const digits = numStr.split('').map(c => charToDigit(c)); const n = digits.length; let body = ''; // Строка с цифрами let line1 = numStr; let line2 = ''; for (let i = 0; i < n; i++) { line2 += String(digits[i]) + ' '; } body += line1 + '' + fromBase + '\n'; body += line2 + '\n'; // Развёрнутая форма body += ' = '; let parts = []; for (let i = 0; i < n; i++) { const power = n - 1 - i; const val = digits[i] * Math.pow(fromBase, power); const digitStr = digits[i] >= 10 ? digitToChar(digits[i]) : digits[i]; if (fromBase >= 10 && digits[i] >= 10) { parts.push('' + digits[i] + ' · ' + fromBase + '' + power + ''); } else { parts.push(digitStr + ' · ' + fromBase + '' + power + ''); } } body += parts.join(' + ') + '\n'; // Вычисляем body += ' = '; let parts2 = []; for (let i = 0; i < n; i++) { const val = digits[i] * Math.pow(fromBase, n - 1 - i); parts2.push('' + val + ''); } body += parts2.join(' + ') + '\n'; // Итог let total = 0; for (let i = 0; i < n; i++) { total += digits[i] * Math.pow(fromBase, n - 1 - i); } body += ' = ' + total + ''; return body; } function stepDivision(decimal, toBase) { if (decimal === 0) return '0'; let body = ''; let steps = []; let current = decimal; while (current > 0) { const quotient = Math.floor(current / toBase); const remainder = current % toBase; steps.push({ quotient, remainder, current }); current = quotient; } steps.forEach((s, idx) => { const isLast = s.quotient === 0; const arrow = isLast ? '← старшая' : ''; const remChar = digitToChar(s.remainder); const remClass = (toBase >= 10 && s.remainder >= 10) ? 'c-orange' : 'c-green'; body += '' + s.current + ' ÷ ' + toBase + ' = ' + s.quotient + ' остаток → ' + remChar + ' ' + arrow + '\n'; }); // Итог — читаем остатки снизу вверх let result = ''; for (let i = steps.length - 1; i >= 0; i--) { result += digitToChar(steps[i].remainder); } body += '\nОтвет (читаем остатки снизу вверх): ' + result + ''; return body; } function stepGrouping(numStr, fromBase, toBase) { numStr = numStr.trim().toUpperCase(); let body = ''; // Сначала переводим в двоичную let decimal = toDecimal(numStr, fromBase); if (decimal === null) return 'Ошибка'; let binary = ''; if (decimal === 0) binary = '0'; else { while (decimal > 0) { binary = (decimal % 2) + binary; decimal = Math.floor(decimal / 2); } } // Определяем размер группы const groupSize = Math.log2(toBase); body += 'Исходное число в двоичной:\n'; body += '' + binary + '2\n\n'; // Группируем let padded = binary; const padLen = (groupSize - (padded.length % groupSize)) % groupSize; if (padLen > 0) { padded = '0'.repeat(padLen) + padded; body += 'Добавляем ведущие нули: ' + padded + '\n\n'; } // Разбиваем на группы let groups = []; for (let i = 0; i < padded.length; i += groupSize) { groups.push(padded.substring(i, i + groupSize)); } body += 'Разбиваем на группы по ' + groupSize + ' бита:\n'; groups.forEach(g => { body += '' + g + ' '; }); body += '\n\n'; // Переводим каждую группу body += 'Переводим каждую группу:\n'; let result = ''; groups.forEach(g => { const val = parseInt(g, 2); const char = digitToChar(val); const charClass = (toBase >= 10 && val >= 10) ? 'c-orange' : 'c-green'; result += char; body += '' + g + ' = ' + parseInt(g, 2) + ' = ' + char + '\n'; }); body += '\nОтвет: ' + result + '' + toBase + ''; return body; } /* ── Рендер результата ───────────────────────────────────── */ function renderResult(numStr, fromBase, toBase, decimal) { const resultEl = document.getElementById('csResult'); resultEl.className = 'cs-result show'; let html = ''; // Главный результат const converted = fromDecimal(decimal, toBase); const toBaseClass = (toBase >= 10) ? 'c-orange' : 'c-green'; html += '
' + converted + '' + toBase + '
'; // Шаг 1: Развёрнутая форма (если переводим в десятичную) if (toBase === 10) { html += '
'; html += '
1 Развёрнутая форма (любая → десятичная)
'; html += '
' + stepExpandedForm(numStr, fromBase) + '
'; html += '
'; } // Шаг 2: Деление с остатком (если переводим из десятичной) if (fromBase === 10) { html += '
'; html += '
2 Деление с остатком (десятичная → ' + toBase + ')
'; html += '
' + stepDivision(decimal, toBase) + '
'; html += '
'; } // Шаг 3: Если переводим между не-десятичными if (fromBase !== 10 && toBase !== 10) { // Шаг 3a: Развёрнутая форма html += '
'; html += '
1 Шаг 1: ' + fromBase + ' → 10 (развёрнутая форма)
'; html += '
' + stepExpandedForm(numStr, fromBase) + '
'; html += '
'; // Шаг 3b: Деление с остатком html += '
'; html += '
2 Шаг 2: 10 → ' + toBase + ' (деление с остатком)
'; html += '
' + stepDivision(decimal, toBase) + '
'; html += '
'; } // Быстрый перевод (только для степеней двойки) const isPowerOf2 = (b) => b > 0 && (b & (b - 1)) === 0; if (isPowerOf2(fromBase) && isPowerOf2(toBase) && fromBase !== toBase) { html += '
'; html += '
⚡ Быстрый перевод через двоичную (группировка битов)
'; html += '
' + stepGrouping(numStr, fromBase, toBase) + '
'; html += '
'; } resultEl.innerHTML = html; resultEl.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } /* ── Ошибки ──────────────────────────────────────────────── */ function showError(msg) { const errEl = document.getElementById('csError'); errEl.textContent = msg; errEl.className = 'cs-error show'; document.getElementById('csResult').className = 'cs-result'; } function hideError() { document.getElementById('csError').className = 'cs-error'; } /* ── Действия ────────────────────────────────────────────── */ function convert() { hideError(); const numStr = document.getElementById('csNumber').value.trim(); const fromBase = parseInt(fromSelect.value, 10); const toBase = parseInt(toSelect.value, 10); if (!numStr) { showError('Введите число.'); return; } if (!isValidForBase(numStr, fromBase)) { showError('Число содержит недопустимые цифры для системы с основанием ' + fromBase + '.'); return; } const decimal = toDecimal(numStr, fromBase); if (decimal === null) { showError('Ошибка преобразования.'); return; } renderResult(numStr, fromBase, toBase, decimal); } function randomTask() { hideError(); const fromBase = Math.floor(Math.random() * 15) + 2; // 2-16 const maxVal = Math.pow(fromBase, 3) - 1; const decimal = Math.floor(Math.random() * maxVal) + 1; const numStr = fromDecimal(decimal, fromBase); const toBase = Math.floor(Math.random() * 15) + 2; document.getElementById('csNumber').value = numStr; fromSelect.value = String(fromBase); toSelect.value = String(toBase); convert(); } function reset() { hideError(); document.getElementById('csNumber').value = '255'; fromSelect.value = '10'; toSelect.value = '2'; document.getElementById('csResult').className = 'cs-result'; } /* ── Инициализация ───────────────────────────────────────── */ document.getElementById('csConvert').addEventListener('click', convert); document.getElementById('csRandom').addEventListener('click', randomTask); document.getElementById('csReset').addEventListener('click', reset); document.getElementById('csNumber').addEventListener('keydown', e => { if (e.key === 'Enter') convert(); });