phpInDev

base_convert

string base_convert ( string numstring, string frombase, string tobase )

base_convert script converts given number numstring from given base frombase to given base tobase. The number must be given as string, even if it was decimal number.

Both frombase and tobase are given as string of characters, in ascending order according to their value, starting from 0. e.g. the number base for decimal would be "0123456789" or the base for hexadecimal would be "0123456789ABCDEF".

NOTE: The script does make difference between capitalized and non capitalized letters. That is, it is possible to have both small and big same letters in the number base meaning different things. But also be careful with things such as hexadecimal. "0123456789abcdef" and "0123456789ABCDEF" are different bases.

Example 1. using base_convert

{ HEX = "0123456789ABCDEF"; DEC = "0123456789"; show_message(base_convert("FFFFFF", HEX, DEC)); }

Shows message:

16777215

Example 2. Binary to ascii conversion

{ BIN = "01"; ASCII = ""; for (i = 0; i < 256; i +=1) { ASCII += chr(i); } msg = "0100100101110100001000000101011101101111011100100110101101110011"; show_message(base_convert(msg, BIN, ASCII)); }

Shows message:

It Works

Code for base_convert.gml

{
    // Variable initialization
    var from_count, to_count, length, divide, number, newlen, result, i;
    
    from_count = string_length(argument1);
    to_count = string_length(argument2);
    result = "";
    
    // Put the given argument into array (array handling is to speed this up)
    length = string_length(argument0);
    for (i = 0; i < length; i += 1)
    {
        number[i] = string_pos(string_char_at(argument0, i + 1), argument1) - 1;
    }
    
    // Loop until whole number is converted
    do
    {
        divide = 0;
        newlen = 0;
        
        // Perform division for the number (divide left with next number)
        for (i = 0; i < length; i+= 1)
        {
            divide *= from_count;
            divide += number[i];
            if (divide >= to_count)
            {
                number[newlen] = divide div to_count;
                newlen += 1;
                divide = divide mod to_count;
            }
            else if (newlen > 0)
            {
                number[newlen] = 0;
                newlen += 1;
            }
        }
        
        length = newlen;
                
        // Add the new gained character to the result string
        result = string_char_at(argument2, divide + 1) + result;
    }
    until (newlen == 0);
    
    return result;
}