base_convert

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

//  Examples
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: Please check the related scripts for several faster conversion scripts for specific bases.

Downloadbase_convert(number,oldbase,newbase)   Returns a string of digits representing the given number converted from one base to another.
/*
**  Usage:
**      base_convert(number,oldbase,newbase)
**
**  Arguments:
**      number      number to be converted, string
**      oldbase     base of the given number, real
**      newbase     desired base of the returned value, real
**
**  Returns:
**      a string of digits representing the given
**      number converted from one base to another
**
**  Notes:
**      Base36 is the largest base supported.
**
**  GMLscripts.com
*/

{
    var number,oldbase,newbase,out,len,tab,i,num,divide,newlen;
    number = string_upper(argument0);
    oldbase = argument1;
    newbase = argument2;
    out = "";
    len = string_length(number);
    tab = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (i=0; i<len; i+=1) {
        num[i] = string_pos(string_char_at(number,i+1),tab)-1;
    }
    do {
        divide = 0;
        newlen = 0;
        for (i=0; i<len; i+=1) {
            divide = divide * oldbase + num[i];
            if (divide >= newbase) {
                num[newlen] = divide div newbase;
                newlen += 1;
                divide = divide mod newbase;
            }else if (newlen  > 0) {
                num[newlen] = 0;
                newlen += 1;
            }
        }
        len = newlen;
        out = string_char_at(tab,divide+1) + out;
    } until (len == 0);
    return out;
}

Click if you've used this script[Please Login]
Projects: 1


comments powered by Disqus