Warcraft III resources & community, 2003–2006 · archived

S2IBase

not rated
Submitted by PepparConversion0 downloads
Converts string s to an integer. Tolerates leading spaces.

Functions like the native S2I, but it can convert strings with any base between 2 and 36.

First the function trims the string from spaces (mini-StringTrimLeft), and in the same time it checks wether the number has a leading minus-sign. If such a sign is encountered, it is removed and a flag is set. Then the function steps through the number until it encounters the end of the string or a character it doesn't recognize. Then it works its way *backwards* through the string, taking the numerical value of each character and multiplying it with the current slot value (m) and adding it to the output integer (i.) After each character is processed the slot value is multiplied with the base. (So the first "slot" value in a hexadecimal number (base 16) would have the value 1, the second 16, the third 256 etc.) At the end of the function, if the sign flag is set, the function returns the negated output integer. If not, the output integer is returned as is.

Tell me if this makes sense. I doubt it does.

Source

function S2IBase takes string s, integer base returns integer
    local string charMap = SubString("0123456789abcdefghijklmnopqrstuvwxyz", 0, base)
    local string str = s
    local string c
    local string a
    local integer i = 0
    local integer p = 0
    local integer d = 0
    local integer m = 1
    local boolean t
    local boolean n
    if base < 2 or base > 36 then
        return 0
    elseif base == 10 then
        return S2I(str)
    endif
    loop
        set c = SubString(str, p, p + 1)
        exitwhen c != " "
        set p = p + 1
    endloop
    if c == "-" then
        set n = true
        set str = SubString(str, p + 1, 65535)
    else
        set n = false
        set str = SubString(str, p, 65535)
    endif
    set p = 0
    loop
        set c = StringCase(SubString(str, p, p + 1), false)
        exitwhen c == "" or c == null
        set t = false
        set d = 0
        loop
            set a = SubString(charMap, d, d + 1)
            exitwhen a == "" or a == null
            if a == c then
                set t = true
                exitwhen true
            endif
            set d = d + 1
        endloop
        exitwhen not t
        set p = p + 1
    endloop
    loop
        exitwhen p == 0
        set c = StringCase(SubString(str, p - 1, p), false)
        set d = 0
        loop
            set a = SubString(charMap, d, d + 1)
            exitwhen a == "" or a == null or a == c
            set d = d + 1
        endloop
        exitwhen a == "" or a == null
        set i = i + d * m
        set m = m * base
        set p = p - 1
    endloop
    if n then
        return -i
    endif
    return i
endfunction

Comments

0

No comments.