I made an algorithm to convert a binary number to an integer, the thing is that I made quite a few lines of code, my solution to that problem is this:
const binaryArrayToNumber = arr => {
let contador = 1;
let bin;
let binArr = [];
for(let i = arr.length - 1; i >= 0; i--){
contador = contador * 2;
bin = contador / 2;
if(arr[i] === 1){
binArr.push(bin);
}
}
for(let i = 0; i < binArr.length; i ++){
if(binArr[i] !== 0){
binArr = binArr.reduce((valorAntetior, valorActual) => valorAntetior + valorActual);
return binArr;
} else {
return 0;
}
}
};
But looking at other solutions I discovered this solution:
const binaryArrayToNumber = arr => {
return parseInt(arr.join(""),2);
};
Could someone explain the last solution to me? I can't understand what is the function of that 2, thanks.
From what I see what is happening is that, first it is written in ECMAScript 6 and then in the mozilla documentation it indicates that:
When you run
arr.join("char")
the array it will be converted to a string separating the values with the specified character or characters, in this case""
or nothing, so the array will look like this (as an example):Then parseInt evaluates if the value is a valid binary representation of it and attempts to convert it to an integer.
So as an example:
I hope it helps you, greetings!
The parseInt function checks the first argument, a string, and attempts to return an integer from the specified base. For example, a base of 10 indicates a conversion to a decimal number, 8 octal, 16 hexadecimal, and so on. For bases greater than 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.
Source: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/parseInt