-2
function calculateBinary(bits) {
var bitValue = 0;

for(var i=0; i<bits.length; i++) {
  if(bits[0] === '1') {
    bitValue += 128;
  } else if (bits[1] === '1') {
    bitValue += 64;
  } else if (bits[2] === '1') {
    bitValue += 32;
  } else if (bits[3] === '1') {
    bitValue += 16;
  } else if (bits[4] === '1') {
    bitValue += 8;
  } else if (bits[5] === '1') {
    bitValue += 4;
  } else if (bits[6] === '1') {
    bitValue += 2;
  } else if (bits[7] === '1') {
    bitValue += 1;
  } 
}
  return bitValue;
}

calculateBinary('11111111');

// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)

Why is my for loop treating every iteration of the bits string as bits[0]? The returned value is '1028' or 12 * 8. What am I doing wrong to cause this in my For loop?

Brixsta
  • 605
  • 12
  • 24
  • I understand this is probably to train, but there is `parseInt('11111111', 2)` (or `Number('0b11111111')`) – ASDFGerte Mar 29 '21 at 01:19

1 Answers1

1

Consider

for(var i=0; i<bits.length; i++) {
  if(bits[0] === '1') {
    bitValue += 128;
  } else if 

You aren't checking the index inside the loop - you're always checking bits[0], and then if that condition doesn't succeed, you're going onto bits[1], etc, without regard to the index.

Remove the loop.

function calculateBinary(bits) {
  var bitValue = 0;
  if (bits[0] === '1') {
    bitValue += 128;
  }
  if (bits[1] === '1') {
    bitValue += 64;
  }
  if (bits[2] === '1') {
    bitValue += 32;
  }
  if (bits[3] === '1') {
    bitValue += 16;
  }
  if (bits[4] === '1') {
    bitValue += 8;
  }
  if (bits[5] === '1') {
    bitValue += 4;
  }
  if (bits[6] === '1') {
    bitValue += 2;
  }
  if (bits[7] === '1') {
    bitValue += 1;
  }
  return bitValue;
}

console.log(calculateBinary('11111111'));

// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)

Or use the index inside the loop to calculate the amount to add.

function calculateBinary(bits) {
  return [...bits].reverse().reduce(
    (a, bit, i) => bit === '0' ? a : a + 2 ** i,
    0
  );
}

console.log(calculateBinary('11111111'));
console.log(calculateBinary('1000'));

(or, even better, don't reinvent the wheel)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320