You are currently viewing the GMLscripts.com static mirror. Forum access and script submissions are not available through this mirror.

Invert GMLscripts.com

fraction_to_bin

Converts a fractional value to a string of binary digits.

bin = fraction_to_bin(0.12500, 5);  //  bin == "00100"
bin = fraction_to_bin(0.65625, 5);  //  bin == "10101"
bin = fraction_to_bin(0.96875, 5);  //  bin == "11111"
fraction_to_bin(fraction, length)
Returns a binary string converted from a decimal fraction.
COPY/// @func   fraction_to_bin(fraction, length)
///
/// @desc   Returns a binary string converted from a decimal fraction.
///
/// @param  {real}      fraction    decimal fraction
/// @param  {real}      length      number of bits to return
///
/// @return {string}    binary digits
///
/// GMLscripts.com/license

function fraction_to_bin(fraction, length) 
{
    var bin = "";

    var i = 1;
    repeat(length) {
        i /= 2;
        if (fraction >= i) {
            fraction -= i;
            bin += "1";
        } else {
            bin += "0";
        }
    }
    return bin;
}

Contributors: Bryan

GitHub: View · Commits · Blame · Raw