Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Conversion in Javascript (Decimal to Binary)

Tags:

javascript

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.

like image 970
Ken Avatar asked Apr 21 '13 15:04

Ken


People also ask

How to convert a decimal to binary in JavaScript?

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.

How do I convert decimal to binary?

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.

What is binary in JavaScript?

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.


1 Answers

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

like image 145
Andbdrew Avatar answered Sep 21 '22 10:09

Andbdrew