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:
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.
function change(name) {
b = document.getElementById("binary").value;
conversion = bin_dec(b);
result.value = conversion;
}
Clearly this is one of the methods for the binary to decimal system in JavaScript, write your method in the comments below.
Some useful links
Indice argomenti tutorial JavaScript