Last active
December 17, 2015 04:10
-
-
Save bmwalters/2853cf4e65d1d6d296f9 to your computer and use it in GitHub Desktop.
anybase^tm calculator (for some reason)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
function ToBase10(num, curbase) -- tonumber has a static charset, we might want to change it in the future so we roll our own | |
local out = 0 | |
num = tostring(num) | |
for i = 1, #num do -- this goes left to right | |
local cur = string.sub(num, i, i) | |
local val = string.find(charset, cur) | |
if not val then error("Number '" .. cur .. "' in base " .. curbase .. " not supported by charset '" .. charset .. "'") return end | |
out = out + (val - 1) * (curbase ^ (#num - i)) | |
end | |
return out | |
end | |
function BaseCalc(num, curbase, targetbase) | |
if not targetbase then | |
targetbase = curbase | |
curbase = 10 | |
end | |
num = ToBase10(num, curbase) | |
local out = "" | |
local mynum = num | |
while true do | |
local cur = math.floor(mynum % targetbase) | |
local val = string.sub(charset, cur + 1, cur + 1) | |
if not val then error("Number '" .. cur .. "' in base " .. targetbase .. " not supported by charset '" .. charset .. "'") return end | |
out = val .. out | |
local nex = math.floor(mynum / targetbase) | |
if nex == 0 then break end | |
mynum = nex | |
end | |
return out | |
end | |
--[[ tests | |
print("0x" .. BaseCalc(10000, 2, 16) == "0x10") | |
print(BaseCalc("ABC", 16, 10) == "2748") | |
--]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment