94 lines
3.0 KiB
HTML
94 lines
3.0 KiB
HTML
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Dec/Bin conversione</title>
|
|
</head>
|
|
|
|
<body>
|
|
<h3>Convertitore Decimale / Binario</h3>
|
|
|
|
Valore decimale:<br>
|
|
<input id="input" placeholder="Inserire valore (0 / 255)"><br>
|
|
<br>
|
|
|
|
C2<br>
|
|
<input id="checkbox" type="checkbox" onclick="checkBox()"><br>
|
|
<br>
|
|
|
|
<button onclick="converti(document.getElementById('input').value)">Converti in binario</button>
|
|
|
|
<p id="c2visual">Non in C2:</p>
|
|
<p id="result"></p>
|
|
</body>
|
|
|
|
<script>
|
|
function checkBox(){
|
|
if(document.getElementById("checkbox").checked){
|
|
document.getElementById("c2visual").innerHTML="In C2:"
|
|
document.getElementById("input").placeholder="Inserire valore (-127 / 127)"
|
|
}
|
|
else{
|
|
document.getElementById("c2visual").innerHTML="Non in C2:"
|
|
document.getElementById("input").placeholder="Inserire valore (0 / 255)"
|
|
}
|
|
}
|
|
|
|
function converti(n){
|
|
let bit2 = ""
|
|
let bit = ""
|
|
|
|
if(document.getElementById("checkbox").checked && n<0){
|
|
|
|
let segno = "0"
|
|
if(n<0){
|
|
segno = "1"
|
|
n *= -1
|
|
}
|
|
for(let i = 0; i < 7; i++){
|
|
if(n%2 === 0){
|
|
bit += 1
|
|
}
|
|
else{
|
|
bit += 0
|
|
}
|
|
if(n%2){
|
|
n -= 1
|
|
}
|
|
n /=2
|
|
}
|
|
let inverti = bit.split('').reverse()
|
|
|
|
for(let j=6; j>=0; j--){
|
|
/*if(bit[j] === 0){*/
|
|
bit2[j] = 1
|
|
/*break
|
|
}*/
|
|
}
|
|
bit = inverti.join('');
|
|
/*for(let j=6; j>=0; j--){
|
|
if(bit.charAt(j) === 0){
|
|
bit.charAt(j) = 1
|
|
break
|
|
}
|
|
}*/
|
|
document.getElementById("result").innerHTML = segno
|
|
document.getElementById("result").innerHTML += bit
|
|
}
|
|
else if(!document.getElementById("checkbox").checked && n<0){
|
|
document.getElementById("c2visual").innerHTML= "ERRORE!"
|
|
document.getElementById("result").innerHTML = "Non è possibile convertire un numero negativo senza Complemento a 2"
|
|
}
|
|
else{
|
|
for(let i = 0; i < 8; i++){
|
|
bit += n % 2
|
|
if(n%2){
|
|
n -= 1
|
|
}
|
|
n /=2
|
|
}
|
|
let inverti = bit.split('').reverse().join ('');
|
|
document.getElementById("result").innerHTML = inverti
|
|
}
|
|
}
|
|
</script>
|
|
</html> |