Warcraft III resources & community, 2003–2006 · archived

BaseConversion

not rated
Submitted by KaTTaNaConversion0 downloads
Converts a number of one base to another base. It's fairly optimized although there may be faster methods.
Parameters:
string input - This is the number which you want converted to another base.
integer inputBase - This is the base of input
integer outputBase - This is the base you want to convert it to.

The bases cannot be longer than the length of charMap, but you can add more characters to it if you want.

If an error occoured, it will return a string telling what went wrong.
Empty strings and null strings return 0.

Source

function BaseConversion takes string input, integer inputBase, integer outputBase returns string
    local string charMap = "0123456789abcdefghijklmnopqrstuvwxyz"
    local string s
    local string result = ""
    local integer val = 0
    local integer i
    local integer p = 0
    local integer pow = 1
    local string sign = ""
    if ( inputBase < 2 or inputBase > StringLength(charMap) or outputBase < 2 or outputBase > StringLength(charMap) ) then
        // Bases are invalid or out of bounds
        return "Invalid bases given"
    endif
    if ( SubString(input, 0, 1) == "-" ) then
        set sign = "-"
        set input = SubString(input, 1, StringLength(input))
    endif
    set i = StringLength(input)
    // Get the integer value of input
    set input = StringCase(input, false)
    loop
        exitwhen i <= 0
        set s = SubString(input, i-1, i)
        set p = 0
        loop
            if ( p >= inputBase ) then
                // Input cannot match base
                return "Input does not match base!"
            endif
            if ( s == SubString(charMap, p, p+1) ) then
                set val = val + pow*p
                set pow = pow * inputBase
                exitwhen true
            endif
            set p = p + 1
        endloop
        set i = i - 1
    endloop
    loop
        set p = ModuloInteger(val, outputBase)
        set result = SubString(charMap, p, p+1) + result
        set val = val / outputBase 
        exitwhen val <= 0
    endloop
    return sign + result
endfunction

Comments

0

No comments.