Skip to content
Advertisement

Only half of array gets raised to power

I wanted to create binary to decimal calculator. When i tried to console log both of arrays (binary is array of 0’s and 1’s, binarypos is array of numbers that are powers of 2.

Screenshot

Then i created simpler version, made in console so chance of making a mistake lowered to zero. But the bug appears again!

const x = Array(8).fill(1);

const xpos = Array(8).fill(0);

for (let i = 0; i < x.length; i++) {
    xpos[x.length - 1 - i] = Number(x[i]);
    xpos[i] = Math.pow(xpos[i] * 2, [i]);
  }
console.log(xpos) // [1, 1, 1, 1, 16, 32, 64, 128]

I want it to look like this

console.log(xpos) // [1, 2, 4, 8, 16, 32, 64, 128]

Advertisement

Answer

Wouldn’t it be simpler to just do something like this?

const x = Array(8).fill(1);
const xpos = [];

for (let i = 0, j=1; i < x.length ; i++, j*=2 ) {
  xpos[i] = j;
}

Or for what your screenshot suggests that you’re trying to accomplish: converting a string of binary digits (0 or 1) into its decimal representation, just:

function binaryToDecimal( digits ) {
  const isValid = /^[01]+$/.test(digits);
  if (!isValid) {
    throw new TypeError("bindDigits must be a string containing only '0' and '1'.");
  }
 
  let value = 0;
  let p = 1;
  for ( const d of digits.split('').map( d => +d ).reverse() ) {
    value += d * p;
    p *= 2;
  }

  return value;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement