I made a few util function that I used for my "write code in chat" system.
Basically, use
intToBase64
to get the string (base 64) for the given integer, and
fromBase64
.
In both cases, you need to know the "maxLength" (how many base64 characters are used for a given field).
In my map, I know that there are less than 64 "waves", so I only need 1 character to represent the wave-number.
I know that the exp is less than 50 000 (or something like that) because that's the amount you have at max-level on my map, so I only need 3 charaters for that, etc.
ofc it is possible to use some other character as separator and do it smarter or whatever, but I made this mostly by myself to learn and it works. I might've looked at how others do certain things, I don't remember.
JASS:
function base64CharFromIndex takes integer index returns string
return SubString("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", index, index + 1)
endfunction
function base64IndexOfChar takes string input returns integer
local integer i = 0
loop
exitwhen base64CharFromIndex(i) == input
set i = i + 1
endloop
return i
endfunction
function intToBase64 takes integer input, integer capResultChars returns string
local integer currentValue = input
local string result = ""
loop
//call BJDebugMsg("current result=" + result + ", currentValue=" + I2S(currentValue))
set result = base64CharFromIndex(ModuloInteger(currentValue, 64)) + result
set currentValue = currentValue / 64
exitwhen currentValue == 0
endloop
//call BJDebugMsg("Final result=" + result + ", currentValue=" + I2S(currentValue))
return SubString(result + "====", 0, capResultChars)
endfunction
function fromBase64 takes string input, integer maxLength returns integer
local integer result = 0
local integer i = 0
local string currentChar
loop
set currentChar = SubString(input, i, i + 1)
exitwhen i > (maxLength - 1) or currentChar == "="
set i = i + 1
set result = result * 64 + base64IndexOfChar(currentChar)
endloop
return result
endfunction
I load by doing (I load the 6th (or 7th? depends how you count I think) character of the chat-string as the wave-number).
set udg_current_wave_nr = fromBase64(SubString(udg_load_string, 6, 7), 1)
I "save" by adding my various values together to something player has to write. There is a description and then:
call BJDebugMsg("-load " + intToBase64(udg_last_market_wave, 1) + intToBase64(udg_last_market_tot_gold, 4) + intToBase64(udg_last_market_exp, 3))
(where udg_last_market_wave, udg_last_market_tot_gold, udg_last_market_exp are the values I store, and the 1, 4, 3 are the "max lengths" I "support").
Note that the code needs to be adjusted if you plan to store values bigger than 64^4 (also known as over 16 million).