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
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
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?
Do you mean you want a script in Javascript that can convert between a numeric in decimal form and the numeric in binary form?
ASKER
pkwan,
Yes, I would like to convert the number 245 in binary!
But I don't know if it's possible!!
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;
}
// 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.
// 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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
function makeBinary(strValue)
{
if(isNaN(strValue)
{
alert("Please enter a valid number!");
}
if(parseFloat(strValue)<1)
{
strValue = false;
}
else
{
strValue = true;
}
return strValue
}