1

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;
    };
2
  • 6
    why don't you just use parseInt with a different radix? es: var a = parseInt("01001011", 2); Commented Aug 6, 2015 at 14:58
  • You've got i++ in the inner loop instead of j++. You can do this without calling Math.pow() too. Commented Aug 6, 2015 at 14:59

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer but this returns the wrong answer Input "011" should give 3 but instead it gives 6
1

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.

2 Comments

Thanks for the reply.What is the effect of adding a comma at var i,value=0;
@mkmkmk4 that just separates separate variables being declared in the var statement. That statement declares i and value. Only value is initialized (to 0); i will be undefined but that's OK because the for loop initializes it.
0

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" />

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.