How to convert binary number to decimal in JavaScript

1 Answer

0 votes
function binary_to_decimal(s) { 
    dec = 0;
   
    for (var i = s.length - 1, j = 0; i >= 0; i--, j++) { 
        if (s[i] === '1') {
            dec += Math.pow(2, j); 
        }
    } 
    return dec; 
} 
     
s = "10101011";  

document.write(binary_to_decimal(s));


 
/*
run:
 
171 
    
*/

 



answered May 10, 2019 by avibootz

Related questions

1 answer 415 views
1 answer 133 views
1 answer 136 views
2 answers 178 views
3 answers 123 views
3 answers 134 views
...