Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
