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
-
Economics & Finance
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.
Method 1: Using Math.pow() with Manual Calculation
This approach calculates the decimal value by iterating through the array and using powers of 2:
const arr = [1, 0, 1, 1];
const binaryArrayToNumber = arr => {
let num = 0;
for (let i = 0, exponent = arr.length - 1; i < arr.length; i++) {
if (arr[i]) {
num += Math.pow(2, exponent);
}
exponent--;
}
return num;
};
console.log(binaryArrayToNumber(arr));
11
Method 2: Using parseInt() with join()
A simpler approach is to join the array elements into a string and use parseInt() with base 2:
const arr = [1, 0, 1, 1];
const binaryArrayToNumber = arr => {
return parseInt(arr.join(''), 2);
};
console.log(binaryArrayToNumber(arr));
11
Method 3: Using reduce() with Bit Shifting
This method uses the reduce function with left bit shifting for efficient calculation:
const arr = [1, 0, 1, 1];
const binaryArrayToNumber = arr => {
return arr.reduce((acc, bit) => (acc << 1) + bit, 0);
};
console.log(binaryArrayToNumber(arr));
11
How It Works
For the binary array [1, 0, 1, 1], the decimal conversion works as follows:
- Position 3 (leftmost): 1 × 2³ = 8
- Position 2: 0 × 2² = 0
- Position 1: 1 × 2¹ = 2
- Position 0 (rightmost): 1 × 2? = 1
- Total: 8 + 0 + 2 + 1 = 11
Comparison
| Method | Performance | Readability | Best For |
|---|---|---|---|
| Math.pow() | Slower | Good | Understanding the concept |
| parseInt() | Fast | Excellent | Simple conversion |
| Bit Shifting | Fastest | Good | Performance-critical code |
Conclusion
The parseInt(arr.join(''), 2) method is the most straightforward approach for converting binary arrays to decimal. For performance-critical applications, consider using the bit shifting method with reduce().
