-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
48 lines (39 loc) · 1.16 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const valorBinarioElement = document.querySelector("#input-texto");
const converterBotao = document.querySelector("#converter");
const resultP = document.querySelector("#result");
function isBinary(val) {
return val.split("").filter((x) => x == "0" || x == "1").length == val.length;
}
function BinaryToDecimal(bin) {
let decimal = 0;
for (let i = bin.length - 1; i >= 0; i--) {
decimal += parseInt(bin[i]) * (Math.pow(2, bin.length - 1 - i));
}
return decimal;
}
converterBotao.addEventListener("click", (e) => {
e.preventDefault();
const valorBinarioValue = valorBinarioElement.value;
let result = 0;
if (valorBinarioValue === "" || !isBinary(valorBinarioValue)) {
resultP.innerHTML = `Digite um número binário válido!`;
} else {
result = BinaryToDecimal(valorBinarioValue);
resultP.innerHTML = `Em Decimal: ${result}`;
}
console.log(result);
});
function DecimalToBinario(decimal) {
var binario = "";
var temp = decimal;
while(temp > 0){
if(temp % 2 == 0){
binario = "0" + binario;
}
else {
binario = "1" + binario;
}
temp = Math.floor(temp / 2);
}
return binario;
}