In this lesson we will learn how to make a binary to decimal conversion in JavaScript.
Try the converter below, write the number and then the conversion will automatically appear in the various systems.
Decimale:
Da zero ad eroe
Entra nel mondo della programmazione web: variabili, funzioni, array, DOM, eventi. Con esercizi pratici e progetti coinvolgenti.
⏱️8 ore di corso registrato
🧩Più di 50 algoritmi risolti passo passo
🎯Livello base — da zero ad eroe
💻100% online, fruibile quando vuoi
Binary to decimal conversion in JavaScript
First of all, let's set up the HTML part of the code.
In our case it will simply be two input boxes:
I have inserted on the input box two events:
onkeyup which uses for the change function;
onkeypress which it uses to check if the number is valid.
Of course I could also handle these events in a different way on the JavaScript side.
We then develop the isValidNumber function, which verifies that the input number is 0 or 1. In this way, if we try to type other numbers or letters they will not be taken into consideration.
function isValidNumber(e) {
if (e.keyCode == 48 || e.keyCode == 49) {
return true;
}
return false;
}
Let's now develop a function that allows you to transform the binary number under consideration into a decimal.
We follow this method:
We transform the number entered in the input field with binary id into a list;
Let's invert the list;
We apply the forEach method to scroll through the list.
Dunquem, for each element we check that the number is 1. If the condition is satisfied, the reference power is added to the decimal variable, obtained thanks to the use of index.
The decimal number obtained is returned.
Here is therefore a possible implementation of the algorithm for binary decimal conversion in JavaScript:
function bin_dec(num){
decimal = 0;
num = Array.from(String(num), Number);
num = num.reverse();
num.forEach((number, index) => {
if (number == 1) {
decimal += Math.pow(2, index);
}
})
return decimal;
}
Now let's create the change function which calls the conversion function.
📚 Consigliato per te
50 Algoritmi per imparare JavaScript
Una guida step by step per imparare JavaScript con esercizi svolti.
Un'email ogni tanto con i nuovi articoli e le guide — niente spam, ti disiscrivi quando vuoi.
🍪 Questo sito usa i cookie
Utilizziamo cookie tecnici necessari al funzionamento e, previo tuo consenso, cookie
analitici e di terze parti per migliorare l'esperienza di navigazione.
Leggi la Cookie Policy e la
Privacy Policy.