RhinoDevel

Software development projects and more.

JavaScript: Convert number to binary (string)

with 2 comments

Create a string holding the binary representation of a number (that is initially converted to a positive integer) with JavaScript:

var decToBinStr = function(n)
{
    var s, i;

    if(n===0.0)
    {
        return String(0);
    }

    i = ~~Math.abs(n); // Positive integer wanted.
    s = '';
    do
    {
        s = i%2 + s;
        i = ~~(i/2); // Integer division.
    }while(i>0);
    return s;
};

The function above creates the binary representation as one would do it with pen and paper.

I implemented it this way to show how you can do it in any programming language.

But if you are interested in a “better” way to do this with JavaScript:

You may also use the >>> (zero-fill right shift) operator to achieve this (or something almost similar..) with less code. See Mozilla and stackoverflow.com.

Advertisements

Written by RhinoDevel

27. June 2017 at 11:03

Posted in Development, JavaScript

Tagged with ,

2 Responses

Subscribe to comments with RSS.

  1. I’m wondering about the “if(n===0.0)” with those three equals signs instead of two. Would it recognize just 0?

    outsourcedguru

    28. June 2017 at 23:59


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: