xxxxxxxxxx
function binaryToDecimal(str){
for (const i of str) {
if (i != 0 && i != 1) {
console.error("Plz provide a valid binary string or array");
return false;
}
};
// it's valid
let arr = Array.from(str);
let pow = [], decimal = 0;
for (let i = 0; i < arr.length; i++) pow.unshift(i);
arr.forEach((v, i) => decimal += v * 2 ** pow[i]);
console.log(decimal);
return decimal;
};
let test1 = "00101100"; // 44
let test2 = "00104100"; // not valid
let test3 = "111111101"; // 509
let test4 = "10000001"; // 129
binaryToDecimal(test4);
xxxxxxxxxx
var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);
xxxxxxxxxx
var binary = "1101000" // code for 104
var digit = binary.toString(10); // Convert String or Digit (But it does not work !)
console.log(digit);
Run code snippet