Reputation: 902
A newbie here! Wondering why the following conversion fails!
var num = prompt("Enter num");
alert(num.toString(2));
If num input is 32. I get 32 as num alert message too.
Upvotes: 27
Views: 49266
Reputation: 2806
Here is my solution that does not use parseInt, but rather a method that shows the logic behind the conversion of decimal to binary.
This method prints the bits to the array which you may later print out if you wish:
var number = 156;
var converted = [];
while(number>=1) {
converted.unshift(number%2);
number = Math.floor(number/2);
}
The converted array will now appear like so:
[1,0,0,1,1,1,0,0]
which of course converts back to 156.
Upvotes: 7
Reputation:
With this function you can specify length of the output.
For example decbin(7,4)
produces 0111
.
function decbin(dec,length){
var out = "";
while(length--)
out += (dec >> length ) & 1;
return out;
}
Upvotes: 20
Reputation: 3297
/** Convert a decimal number to binary **/
var toBinary = function(decNum){
return parseInt(decNum,10).toString(2);
}
/** Convert a binary number to decimal **/
var toDecimal = function(binary) {
return parseInt(binary,2).toString(10);
}
Finally use it
var num= prompt("Enter num");
alert(toBinary(num));
Upvotes: 6
Reputation: 11895
try
(+num).toString(2)
,
Number(num).toString(2)
or
parseInt(num, 10).toString(2)
Any of those should work better for you.
The issue is that the toString
method of javascript Number
objects overrides the toString
method of Object
objects to accept an optional radix as an argument to provide the functionality you are looking for. The String
object does not override Object
's toString
method, so any arguments passed in are ignored.
For more detailed information about these objects, see the docs at Mozilla:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Methods
or W3 schools:
http://www.w3schools.com/jsref/jsref_tostring_number.asp http://www.w3schools.com/jsref/jsref_obj_string.asp
Upvotes: 43
Reputation: 27346
Cast it to an integer first. At the moment you're converting a string to it's binary representation.
num = +num;
Upvotes: 5