0

I was trying to create a binary to decimal converter without using parseInt ()

Heres my code :

var inp = `110010`;

    var len = inp.length;

    var string = inp.split("");

    var counter = string.map(function(val,i){
     return i;  
    }).reverse();

    var storeBin = string.map(function(val,i){

    let x ="";


    if(val>0){
    x += 2;
    }else if(val===0){
    x += 0;
    }

    return Math.pow(string[i]*x,counter[i]);

    });


    var dec=0; /* output */



    for(i=0;i<len;i++){
    dec += storeBin[i]
    }
   console.log("Entered binary "+inp);
  console.log("Decimal "+dec);

When I run it:

   Input: 1010

  Output: Entered binary 1010
                Decimal 11

But the output of binary 1010 should be 10 now 11 can someone please help me find the issue in this code

Subha Jeet Sikdar
  • 446
  • 1
  • 4
  • 15

1 Answers1

0

You need to do it like return val * Math.pow(2, counter[i]);.

var inp = `110010`;

var len = inp.length;

var string = inp.split("");

var counter = string.map(function(val, i) {
  return i;
}).reverse();

var storeBin = string.map(function(val, i) {
  return val * Math.pow(2, counter[i]);
});


var dec = 0; /* output */



for (i = 0; i < len; i++) {
  dec += storeBin[i]
}
console.log("Entered binary " + inp);
console.log("Decimal " + dec);

FYI : The correspomding deciaml number to a binary number is the sum of binary digits (dn) times their power of 2 (2^n):

decimalNum = d0 × 2^0 + d1 × 2^1 + d2 × 2^2 + ...

Even you can make it more simpler by using the Array#reduce method.

var inp = `110010`;

var dec = inp.split('').reduce(function(val, d, i, arr) {
  return val + Math.pow(2, arr.length - i - 1) * d;
}, 0);


console.log("Entered binary " + inp);
console.log("Decimal " + dec);

Or with Array#reverse method.

var inp = `110010`;

var dec = inp.split('').reverse().reduce(function(val, d, i) {
  return val + Math.pow(2, i) * d;
}, 0);


console.log("Entered binary " + inp);
console.log("Decimal " + dec);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188