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

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 24-Aug-2020 10:00:47
Advertisements