0

I am extremely new to programming and have ran into a slight problem.

I am trying to convert any base 10 number to a base 2 number using JavaScript. In my code I am using "intDividend" to represent any integer between 1 and 1024 that the user inputs into the equation.

I believe I need to use a while loop instead of a for loop, however when I typed everything out, I was not able to get any answer to pop up into the text box I created on my webpage.

I can't figure out what is wrong and nothing I research seems to lead me in the right direction. This is the code that I have come up with.

function Base10ToBase2(intDividend) {
  var fltQuotient=1.0
  var intQuotient=1
  var intRem=0
  var fltDiff=0.0
  var strB2=" "

  while (intDividend != 0) {
    fltQuotient=intDividend/2
    intQuotient=parseInt(fltQuotient)
    fltDiff=fltQuotient-intQuotient
    if (fltDiff == 0) {
     intRem=0
    }
    else {
     intRem = 1
    }
    strB2 = intRem + strB2
    intDividend=intQuotient
  }
 ConvertForm.BaseOutput.value=strB2;
} 
waltweave
  • 3
  • 1
  • The real question is "why". Or rather why not just use `Number(123).toString(2)` – Petah Jul 15 '16 at 03:51
  • your function *is* working. If I replace `ConvertForm.BaseOutput.value=strB2;` for `console.log(strB2)` I get the right binary. – Gerardo Furtado Jul 15 '16 at 03:58
  • http://stackoverflow.com/questions/1337419/how-do-you-convert-numbers-between-different-bases-in-javascript – Sam Axe Jul 15 '16 at 04:27
  • I just started a summer class and my Professor wants me to do it this way. If I have the formula right, I must be messing up something somewhere else in my code. – waltweave Jul 15 '16 at 15:00

0 Answers0