We help IT Professionals succeed at work.

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

on
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
Comment
Watch Question

## View Solution Only

BRONZE EXPERT
Top Expert 2005

Commented:
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)
{
}

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

Analyst Programmer

Commented:
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?

Commented:
pkwan,

Yes, I would like to convert the number 245 in binary!
But I don't know if it's possible!!
Analyst Programmer

Commented:
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;
}
Analyst Programmer

Commented:
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.
Commented:

<html>
<title>Binary - Numeric</title>
<script language="javascript">
<!--
function toBinair(sNumeric)
{
var sValue="";
// is not a number?
if(isNaN(sNumeric)) return "is Not a Number";
// ok
var iValue=sNumeric;

for(i=0;i<8;i++)
{
sValue = ""+((iValue%2)==0?0:1)+sValue;
iValue = iValue >> 1;
}

return sValue;
}

function toInteger(sBinair)
{
if(isNaN(sBinair)) return "is Not a Number";
var iValue=sBinair;
// check for 1's and 0's
for(i=0;i<iValue.length;i++)
if(!(iValue.charAt(i)=="0" || iValue.charAt(i)=="1")) return "is Not a Number";

var sValue=0;
var iLastValue=1;
for(i=iValue.length-1;i>=0;i--)
{
sValue += ((iValue%2)==0?0:iLastValue);
iValue = iValue.substring(0,i);
iLastValue *= 2
}

return sValue;
;
}
//-->
</script>

<body bgcolor="white">
<form onSubmit="return false">
<table border=1>
<tr>
<td>Numeric: </td>
<td><input type=text onKeyUp="this.form.fBinair.value=toBinair(this.value);" name="fNumeric" value=""></td>
</tr>
<tr>
<td>Binair: </td>
<td><input type=text onKeyUp="this.form.fNumeric.value=toInteger(this.value);" name="fBinair" value=""></td>
</tr>
</table>
</form>
</body>

</html>