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.
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);
0 as initial value, you can just omit it.r one bit left, that means, the value is like multiplied with two and then a bitwise or is performed with a.