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.
Then i created simpler version, made in console so chance of making a mistake lowered to zero. But the bug appears again!
JavaScript
x
10
10
1
const x = Array(8).fill(1);
2
3
const xpos = Array(8).fill(0);
4
5
for (let i = 0; i < x.length; i++) {
6
xpos[x.length - 1 - i] = Number(x[i]);
7
xpos[i] = Math.pow(xpos[i] * 2, [i]);
8
}
9
console.log(xpos) // [1, 1, 1, 1, 16, 32, 64, 128]
10
I want it to look like this
JavaScript
1
2
1
console.log(xpos) // [1, 2, 4, 8, 16, 32, 64, 128]
2
Advertisement
Answer
Wouldn’t it be simpler to just do something like this?
JavaScript
1
7
1
const x = Array(8).fill(1);
2
const xpos = [];
3
4
for (let i = 0, j=1; i < x.length ; i++, j*=2 ) {
5
xpos[i] = j;
6
}
7
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:
JavaScript
1
16
16
1
function binaryToDecimal( digits ) {
2
const isValid = /^[01]+$/.test(digits);
3
if (!isValid) {
4
throw new TypeError("bindDigits must be a string containing only '0' and '1'.");
5
}
6
7
let value = 0;
8
let p = 1;
9
for ( const d of digits.split('').map( d => +d ).reverse() ) {
10
value += d * p;
11
p *= 2;
12
}
13
14
return value;
15
}
16