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 binary 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 library methods

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));

Method 2: Reducing the array

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.

The code for this using Bitwise Operator −

Example

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

Output

The output in the console will be −

11

Updated on: 26-Aug-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements