Convert an array of binary numbers to corresponding integer in JavaScript

Let's say, we have an array of Numbers that contains 0 and 1 ?

const arr = [0, 1, 0, 1];

We are required to write an Array function, toBinary() that returns the corresponding decimal integer for the array it is used with.

For example ? If the array is ?

const arr = [1, 0, 1, 1];

Then the output should be 11 because the decimal representation of binary 1011 is 11.

Therefore, let's write the code for this function.

Method 1: Using parseInt() with join()

In JavaScript, there exists a method parseInt(), that takes in two arguments first one is a string and second a number that represents a particular base, like 10 for decimal base, 2 for binary. This function parses the string argument and returns an integer of the specified radix (base).

In our case, to convert the array of binary to decimal, we can use the parseInt() function like this ?

const arr = [1, 0, 1, 1];
const parseArray = arr => {
    const binaryString = arr.join("");
    return parseInt(binaryString, 2);
};
console.log(parseArray(arr));
11

Method 2: Using reduce() with Bitwise Operators

In this method we iterate over the binary array and construct a decimal based on the corresponding binary numbers. We will use the left shift operator (<<) to shift the accumulated value to left by one bit every time and return the bitwise OR (|) of the shifted accumulated value and current value.

const arr = [1, 0, 1, 1];
const parseArray = arr => {
    return arr.reduce((acc, val) => {
        return (acc << 1) | val;
    });
};
console.log(parseArray(arr));
11

Method 3: Using Mathematical Approach

We can also convert binary to decimal using mathematical calculation where each bit is multiplied by powers of 2.

const arr = [1, 0, 1, 1];
const parseArray = arr => {
    let decimal = 0;
    const length = arr.length;
    
    for (let i = 0; i < length; i++) {
        decimal += arr[i] * Math.pow(2, length - 1 - i);
    }
    return decimal;
};
console.log(parseArray(arr));
11

Comparison

Method Performance Readability Best For
parseInt() + join() Good High Simple conversion
reduce() + Bitwise Excellent Medium Performance-critical code
Mathematical Good High Educational purposes

Conclusion

The parseInt() method is most readable, while the bitwise reduce() approach offers the best performance. Choose based on your specific needs and team preferences.

Updated on: 2026-03-15T23:18:59+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements