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.
The parseInt() method is used to convert a string value to an integer. The JavaScript built-in method toString([radix]) returns a string value in a specified radix (base). Here, toString(2) converts the decimal number to binary number.
Take decimal number as dividend. Divide this number by 2 (2 is base of binary so divisor here). Store the remainder in an array (it will be either 0 or 1 because of divisor 2). Repeat the above two steps until the number is greater than zero.
JavaScript Bitwise Operations JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With