Solved

So here is a interesting question

Posted on 2014-01-19
3
161 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 82

Accepted Solution

by:
leakim971 earned 250 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 83

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 250 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: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering 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

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
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…

789 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