RANDOM DONUT
RANDOM DONUT

Reputation: 23

'Binary number number to base-10' program

In my es6 compiler, I was working on a function that converts any binary number into a base-10 number. basically, the 1s and 0s are all defaulting to 1.

This project is just 4 a 12-yr-old's pleasure (me) so, no rush if there's someone else with something for their job. anyway, I found the problem was in the fact that when you entered the binary number, the numbers stored in convertedNumQuery somehow defaulted to 1, even if the number was 0. I've tried debugging everywhere, but maybe it's just cause i'm a newb >.<

var numQuery = prompt("Enter a binary number to convert to base-10! Don't leave the \"0b\" in there.").split("");
var binaryChart = [1];
var convertedNumQuery = numQuery.map(Number);
var base10 = 0;
console.log(convertedNumQuery+ "\n");
for (var i = 0; i < (numQuery.length - 1); i++) {
    binaryChart.unshift(binaryChart[0]*2);
    console.log(binaryChart);
}
console.log(convertedNumQuery);
console.log("\n convertedNumQuery is array: " + Array.isArray(convertedNumQuery));
for (var i = 0; i < convertedNumQuery.length; i++ ) {
    if (convertedNumQuery[i] = 1) {
        base10 += binaryChart[i];
        console.log(convertedNumQuery[i]);
    }
}
console.log(base10);

say the binary number I wanted to convert is 101010, or 42. the expected result, 42, is supposed to be stored in base10, but what ends up happening is every number in binaryChart is added to get 63. and even stranger, when I looked at convertedNumQuery in line 15 console.log(convertedNumQuery[i]);, the array was logged in the console as all 1s.

Upvotes: 1

Views: 134

Answers (1)

Aziz.G
Aziz.G

Reputation: 3721

why don't just use parseInt to convert:

params : (number,base)

console.log(parseInt(110101, 2))

Upvotes: 4

Related Questions