Invert GMLscripts.com

dec_to_bin

Converts a decimal value to a string of binary digits.

bin = dec_to_bin(123);          //  bin == "1111011"
bin = dec_to_bin(456);          //  bin == "111001000"
bin = dec_to_bin(789, 16);      //  bin == "0000001100010101"
bin = dec_to_bin(-43, 16);      //  bin == "1111111111010101"
dec_to_bin(dec, len)
Returns a given value as a string of binary digits.
COPY/// @func   dec_to_bin(dec, len)
///
/// @desc   Returns a given value as a string of binary digits.
///         Binary strings can be padded to a minimum length.
///         Note: If the given value is negative, it will
///         be converted using its two's complement form.
///
/// @param  {real}      dec         integer
/// @param  {real}      [len=1]     minimum number of digits
///
/// @return {string}    binary digits
///
/// GMLscripts.com/license

function dec_to_bin(dec, len = 1) 
{
    var bin = "";

    if (dec < 0) {
        len = max(len, ceil(logn(2, 2 * abs(dec))));
    }

    while (len-- || dec) {
        bin = ((dec & 1) ? "1" : "0") + bin;
        dec = dec >> 1;
    }

    return bin;
}

Contributors: xot

GitHub: View · Commits · Blame · Raw