JavaScript program to take in a binary number as a string and returns its numerical equivalent in base 10



We are required to write a JavaScript function that takes in a binary number as a string and returns its numerical equivalent in base 10. Therefore, let’s write the code for the function.

This one is quite simple, we iterate over the string using a for loop and for each passing bit, we double the number with adding the current bit value to it like this −

Example

const binaryToDecimal = binaryStr => {    let num = 0;    for(let i = 0; i < binaryStr.length; i++){       num *= 2;       num += Number(binaryStr[i]);    };    return num; }; console.log(binaryToDecimal('1101')); console.log(binaryToDecimal('1101000')); console.log(binaryToDecimal('10101'));

Output

The output in the console will be −

13 104 21
Updated on: 2020-08-24T10:01:56+05:30

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements