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
Binary array to corresponding decimal in JavaScript
Problem
We are required to write a JavaScript function that takes in a binary array (consisting of only 0 and 1).
Our function should first join all the bits in the array and then return the decimal number corresponding to that binary.
Example
Following is the code −
const arr = [1, 0, 1, 1];
const binaryArrayToNumber = arr => {
let num = 0;
for (let i = 0, exponent = 3; i < arr.length; i++) {
if (arr[i]) {
num += Math.pow(2, exponent);
};
exponent--;
};
return num;
};
console.log(binaryArrayToNumber(arr));
Output
11
Advertisements
