RhinoDevel

Software development projects and more.

Archive for the ‘JavaScript’ Category

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 ,

%d bloggers like this: