Link to home
Start Free TrialLog in
Avatar of ldanet
ldanet

asked on

convert a numeric number in binary and a binary in numeric?

Hello !

Is it possible to convert it javascript a numeric number in binary and a binary in numeric ?

If yes how should to me proceed?

thanks much!

Ankou
Avatar of fritz_the_blank
fritz_the_blank
Flag of United States of America image

You can use the parseInt and parseFloat functions to cast a variable to integer and numberic respectively. As for converting numberic to binary, I don't know of a native JavaScript function to do this, but something like:

function makeBinary(strValue)
{
if(isNaN(strValue)
   {
   alert("Please enter a valid number!");
   }

if(parseFloat(strValue)<1)
   {
   strValue = false;
   }
else
   {
   strValue = true;
   }
return strValue
}

Ankou,

Do you mean you want a script in Javascript that can convert between a numeric in decimal form and the numeric in binary form?
Avatar of ldanet
ldanet

ASKER

pkwan,

Yes, I would like to convert the number 245 in binary!
But I don't know if it's possible!!
Here is the code:
// bin to dec
function todec(binstr) {
  var i;
  var dec=0;

  for (i=binstr.length-1; i>=0; i--) {
    dec += parseInt(binstr.substr(i, 1))*Math.pow(2, binstr.length-1-i);
  }
  return dec;
}

// dec to bin
function tobin(decstr) {
   var i = parseInt(decstr);
   var binstr = "";

   if (i==0)
     return binstr;

   while (i > 0) {
     if (i%2 == 0)
       binstr = "0" + binstr;
     else
       binstr = "1" + binstr;
     i = Math.floor(i/2);
   }

  return binstr;
}
correction:

// dec to bin
function tobin(decstr) {
  var i = parseInt(decstr);
  var binstr = "";

  if (i==0)
    return "0";

  while (i > 0) {
    if (i%2 == 0)
      binstr = "0" + binstr;
    else
      binstr = "1" + binstr;
    i = Math.floor(i/2);
  }

 return binstr;
}

Another note: This works with non-negative integer only.
ASKER CERTIFIED SOLUTION
Avatar of CJ_S
CJ_S
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial