Solved

So here is a interesting question

Posted on 2014-01-19
3
155 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
Comment Utility
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 82

Expert Comment

by:Dave Baldwin
Comment Utility
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 42

Assisted Solution

by:Rob Jurd, EE MVE
Rob Jurd, EE MVE earned 250 total points
Comment Utility
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
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…

728 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now