School-HTML/3AIN/Verifica TPS JavaScript 22-.../Esercizio2.html

62 lines
1.7 KiB
HTML

<!-- Manuel Vichi 3^AIN - Esercizio 2 -->
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Convertitore Base 10 a Base 16</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 30px;
}
input, button {
padding: 10px;
margin: 10px 0;
}
label {
font-weight: bold;
}
.result {
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Convertitore Base 10 a base 16</h1>
<label for="num">Inserisci un numero in base 10:</label>
<input type="number" id="num" required>
<p>In caso di numero decimale esso viene automaticamente arrotondato.</p>
<button onclick="converti()">Converti</button>
<div class="result">
<p><strong>Base 16:</strong> <span id="hexResult"></span></p>
</div>
<script>
function converti() {
let original = document.getElementById("num").value;
let num = parseInt(original);
if (num < 0) {
alert("Il numero deve essere positivo!");
return;
}
function esadec(n) {
const hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
let hex = '';
while (n > 0) {
hex = hexChars[n % 16] + hex;
n = parseInt(n / 16);
}
return hex === '' ? '0' : hex;
}
let hexResult = esadec(num);
document.getElementById("hexResult").textContent = hexResult;
}
</script>
</body>
</html>