1

I had to resort to doing this at one point:

var bytes = [ 1, 0, 1, 0, 0, 0, 1, 0 ]
var integer = parseInt(bytes.join(''), 2)

However, I am wondering if there is a more optimal/proper way of doing this in JavaScript rather than converting it to a string and parsing it. In addition to asking how to do the above and turn it into an integer, I would also like to know how to turn it into a bytearray. Something like this:

var bytes = [ 1, 0, 1, 0, 0, 0, 1, 0 ]
var bytearray = new Uint8Array(bytes)
var integer = bytearray.toInteger()
Lance
  • 75,200
  • 93
  • 289
  • 503
  • What do you mean by "byte array"? What is the expected output? – guest271314 Feb 06 '19 at 14:15
  • 1
    it does not work this way, because your bytes array is a bit array. – Nina Scholz Feb 06 '19 at 14:17
  • 1
    Possible duplicate of [Convert binary representation of number from string to int -Javascript](https://stackoverflow.com/questions/11103487/convert-binary-representation-of-number-from-string-to-int-javascript) – ControlAltDel Feb 06 '19 at 15:37

2 Answers2

2

Maybe you could use reduce(), this will loop once on the array (thing you already doing when calling join() plus the overhead of then calling parseInt()). However, your solution is shorter.

var bits = [ 1, 0, 1, 0, 0, 0, 1, 0 ];
var integer = parseInt(bits.join(''), 2);

console.log("Your solution: " + integer);

var int = bits.reduce(
    (a, bit, i, arr) => a + (bit ? Math.pow(2, arr.length - i - 1) : 0),
    0
);

console.log("My solution: " + int);
Shidersz
  • 16,846
  • 2
  • 23
  • 48
1

The formula to convert a binary byte array to an integer is (pseudocode)

let power = 1;
var intVal = 0;
for (i = [interate from lowdigit to highdigit]) {
  if (array[i]) intVal += power;
  power *= 2;
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • 1
    And why is this better than `parseInt(bytes.join(''), 2)` which is much simpler and more intuitive? – Alexandre Elshobokshy Feb 06 '19 at 14:20
  • @IslamElshobokshy I have actually deleted an answer with this solution. The answer is (a) the parseInt solution only works if the low bit / high bit ordering is set correctly. (b) creating a string and then parsing it creates a least 1 extra object (depending on the javascript engine) and then that object only exists to be parsed. What I've posted is the verbose but more efficient and clear (maybe) way to do it – ControlAltDel Feb 06 '19 at 14:27