?
Solved

So here is a interesting question

Posted on 2014-01-19
3
Medium Priority
?
169 Views
Last Modified: 2014-01-21
So did a interview and the question was without using any native browser functions convert a decimal to binary format in JavaScript.   I didn't know that off hand.
0
Comment
Question by:stargateatlantis
3 Comments
 
LVL 83

Accepted Solution

by:
leakim971 earned 1000 total points
ID: 39793275
Test page : http://jsfiddle.net/uLH2B/
var d = 8;
var b = "";
while(d>0) {
    b = d%2 + b;
    d = d>>1;
}
alert( b );

Open in new window

0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 39793278
Since javascript is weakly typed like PHP is, I usually just add 0 or mulitply by 1.  But then... javascript doesn't actually have a 'decimal' format.  It's strings or numbers with automatic provisions for int or float.

http://www.w3schools.com/js/js_datatypes.asp
0
 
LVL 43

Assisted Solution

by:Rob
Rob earned 1000 total points
ID: 39793445
This converts the decimal part as well:

http://jsbin.com/uKAMiXUC/1/edit?js,console

var n = "8.75";
var a = n.split(".");
var i = a[0]*1;
var den = 1;
for (j=0;j<a[1].length;j++) {
  den = den * 10;
}
var d = a[1]/den;

var b1 = "";
var b2 = "";

while(i>0) {
  b1 = i%2 + b1;
  i = i>>1;
}

var tmp = 0;
while(d>0) {
  tmp = ("" + d*2 + "").split(".");
  b2 = b2 + tmp[0];
  d = tmp[1] / 10;
}
console.log( b1 + "." + b2 );

Open in new window

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question