- Joined
- Oct 12, 2008
- Messages
- 1,570
CodeConverter
What is CodeConverter?
CodeConverter is a function which can convert any x-base code into an y-base code. Confusing? I shall explain.
Our normal number system is a 10-base code, meaning it has 10 different characters (0,1,2,3,4,5,6,7,8,9,0). When you think about numbers, you think them in a 10-base number normally, but when a computer thinks, he thinks in a 2-base number, binary code.
This function can convert an x-base number into an y-base number, with for x and y any number higher than 1.
The code
JASS:
library CodeConverter
function ConvertCode takes integer amount, integer oldbase, integer newbase returns integer
local integer i = 0
local integer i2 = 0
local integer current = 0
local string amounts = I2S(amount)
local integer length = StringLength(amounts)
local string c
local integer plus = StringLength(I2S(oldbase))
// no x-base or y-base number can be made when x or y are below 2
if oldbase < 2 or newbase < 2 then
return -1
endif
// Why would you want to convert to the same base?
if oldbase == newbase then
return amount
endif
// First we convert to 10-base. But if the old base is already 10, there is no need.
if oldbase != 10 then
loop
set c = SubString(amounts,length-plus-(i*plus),length-(i*plus))
exitwhen c == "" or length-i == 0
set current = current + (S2I(c)*R2I(Pow(oldbase,i)))
set i = i + 1
endloop
set i = 0
endif
// Now we convert to y-base, but if y is 10, we dont need to, because we already did that above.
if newbase != 10 then
set c = ""
loop
exitwhen Pow(newbase,i) > current
set i = i + 1
endloop
set i = i - 1
loop
exitwhen i < 0
if current >= Pow(newbase,i) then
loop
exitwhen current < Pow(newbase,i)
set i2 = i2 + 1
set current = current - R2I(Pow(newbase,i))
endloop
endif
set c = c + I2S(i2)
set i2 = 0
set i = i - 1
endloop
return S2I(c)
else
return current
endif
return -1
endfunction
endlibrary
A question to you:
What will actually happen when I insert a negative number? Currently it will return the converted number, only positive. should it return negative or positive?
Confession
This can probably be done alot easier without converting to 10-base first, but I do not have the knowledge how to.
-Yixx,,-
Last edited: