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

Invert GMLscripts.com

base_convert

This script is used to convert integer values between to arbitrary bases. The numbers are supplied and returned as strings and the bases are supplied as integers.

n = base_convert("789", 10, 8);  //  decimal to octal returns "1425"
n = base_convert("abc", 16, 10); //  hex to decimal returns "2748"
n = base_convert("123", 10, 2);  //  decimal to binary returns "1111011"

NOTE: Check related scripts for several faster conversions of specific bases.

base_convert(number, oldbase, newbase)
Returns a number converted from one base as another base.
COPY/// @func   base_convert(number, oldbase, newbase)
///
/// @desc   Returns a number converted from one base as another base.
///         Base36 is the largest base supported.
///
/// @param  {string}    number      integer value to be converted
/// @param  {real}      oldbase     base of the given number
/// @param  {real}      newbase     base of the returned number
///
/// @return {string}    number
///
/// GMLscripts.com/license

function base_convert(number, oldbase, newbase) {
    number = string_upper(number);

    var dig = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var len = string_length(number);

    var num;
    for (var i = 0; i < len; i++) {
        num[i] = string_pos(string_char_at(number, i + 1), dig) - 1;
    }

    var out = "";
    while (len > 0) {
        var divide, newlen;
        divide = 0;
        newlen = 0;
        for (var i = 0; i < len; i++) {
            divide = divide * oldbase + num[i];
            if (divide >= newbase) {
                num[newlen] = divide div newbase;
                newlen++;
                divide = divide mod newbase;
            } else if (newlen > 0) {
                num[newlen] = 0;
                newlen++;
            }
        }
        len = newlen;
        out = string_char_at(dig, divide + 1) + out;
    }

    return out;
}

Contributors: xot

GitHub: View · Commits · Blame · Raw