mkmkmk4
mkmkmk4

Reputation: 31

Binary to Decimal Javascript

This code is supposed to take in a string ("100101") and output the result in decimal.I'm not quite sure why it's not working.Any help would be appreciated.

function BinaryConverter(str) { 
 var num=str.split("");
 var powers=[];
 var sum=0;
  for(var i=0;i<num.length;i++){
   powers.push(i);
}
 for(var i=powers.length-1;i>=0;i--){
  for(var j=0;j<num.length;i++){
   sum+=Math.pow(2,i)*num[j];
  }
 }
 return sum;
};

Here's my updated code below .For an input "011" it should do( 2^2*0 +2^1*1 +2^0*1)to =3 but it returns 14.Anybody know where I'm going wrong?

    function BinaryConverter(str) { 
     var num=str.split("");
     var powers=[];
     var sum=0;
     for(var i=0;i<num.length;i++){
       powers.push(i);
     }
     for(var i=powers.length-1;i>=0;i--){
      for(var j=0;j<num.length;j++){
       sum+=Math.pow(2,i)*num[j];
      }
     }
     return sum;
    };

Upvotes: 1

Views: 1903

Answers (4)

anshul
anshul

Reputation: 113

Here is the simple implementation of binary to decimal in javascript.

main();

function main() {
    let binaryInput = 10000100111;
    let decimalOutput = binaryTodecimal(binaryInput);
    console.log(decimalOutput);
}

function binaryTodecimal(input) {
    let inputString = input.toString();
    let result = 0;
    let exponent = 1;
    let currentBit = 0;
    for (let i = inputString.length - 1; i >= 0; i--) {
        currentBit = parseInt(inputString[i]);
        currentBit *= exponent;
        result += currentBit;
        exponent *= 2;
    }
    return result;
}

Upvotes: 0

BeyelerStudios
BeyelerStudios

Reputation: 4283

ace040686 only inverted the pow(2,i) and num[len-1-i] in his answer, otherwise it would be correct. Also you're pushing 0..str.length-1 unnecessarily to powers, those are implicit indices.

function convertNaive(str) {
  var num = str.split("");
  var len = num.length;
  var sum = 0;
  for(var i = len - 1; i >= 0; --i)
    sum += Math.pow(2, len - 1 - i) * num[i];
  return sum;
}

You can improve this a bit to avoid the unnecessary array and especially Math.pow:

function convertImproved(str) {
  var len = str.length;
  var sum = 0;
  for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
    sum += fac * str[len - 1 - i];
  return sum;
}

Try it yourself:

var input = "100101";
var logNode = document.getElementById("log");

function log(line) {
  var text = document.createTextNode(line);
  var node = document.createElement("p");
  node.appendChild(text);
  logNode.appendChild(node);
}

function convertNaive(str) {
  var num = str.split("");
  var len = num.length;
  var sum = 0;
  for(var i = len - 1; i >= 0; --i)
    sum += Math.pow(2, len - 1 - i) * num[i];
  return sum;
}

function convertImproved(str) {
  var len = str.length;
  var sum = 0;
  for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
    sum += fac * str[len - 1 - i];
  return sum;
}

log("input: " + input);
log("parseInt(input, 2): " + parseInt(input, 2));
log("convertNaive(input): " + convertNaive(input));
log("convertImproved(input): " + convertImproved(input));
<div id="log" />

Upvotes: 0

ace040686
ace040686

Reputation: 163

The two nested for loops have a problem. The first one subtracts an i, while the second adds an i forever creating a never ending loop.

ALSO your code should be this:

    function BinaryConverter(str) { 
        var num=str.split("");
        var powers=[];
        var sum=0;
        var numlength=num.length;

        for(var i=0;i<num.length;i++){
            powers.push(i);
        }

        for(var i=powers.length-1;i>=0;i--){

            sum+=Math.pow(2,i)*num[numlength-i-1];

        }
        return sum;
   };

I don't think you need the nested for loop

Upvotes: 1

Pointy
Pointy

Reputation: 413720

If you don't want to do that with parseInt() for some reason (like, because the homework problem says you can't), you can do this without the complexity and expense of calling Math.pow() for each digit:

function parseBinary(str) {
  var i, value = 0;
  for (i = 0; i < str.length; ++i)
    value = value * 2 + +str[i];
  return value;
}

That doesn't check for invalid input strings.

Upvotes: 1

Related Questions