1

How to convert an array of binary numbers that have only 1 and 0 to a corresponding number? Like

var binArray  = [1, 0, 1, 1] ;
output = 11;

I know I need to use bitwise operators >> << somehow, but I don't how.

2 Answers 2

3

You can use parseInt() alongwith base or radix argument like this:

> var binArray = [1, 0, 1, 1]
> binArray.join('')
"1011"
> parseInt(binArray.join(''), 2)
11
> parseInt("101", 2)
5
Sign up to request clarification or add additional context in comments.

Comments

2

You could use Array#reduce and a left shift operator <<.

                     return
     r       a     dec     bin
------  ------  ------  ------
     1       0       2      10
     2       1       5     101
     5       1      11    1011

var binArray = [1, 0, 1, 1],
    output = binArray.reduce(function (r, a) {
        return (r << 1) | a;
    });

console.log(output);

ES6

var binArray = [1, 0, 1, 1],
    output = binArray.reduce((r, a) => (r << 1) | a);

console.log(output);

3 Comments

FWIW, you don't have to pass 0 as initial value, you can just omit it.
Thanks for this, could you explain me what means (r << 1) | a?
it shifts the value of r one bit left, that means, the value is like multiplied with two and then a bitwise or is performed with a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.