Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- https://github.com/oploadk/base2base for computercraft
- local fmt = string.format
- local function next_power(p, base_from, base_to)
- local r, j, t = {}
- for i = 1, #p do
- j, t = i, p[i] * base_from
- while true do
- t = (r[j] or 0) + t
- r[j] = t % base_to
- t = math.floor(t / base_to)
- if t == 0 then break end
- j = j + 1
- end
- end
- return r
- end
- -- a = a + n * b
- local function add_times(a, n, b, base)
- local j, t
- for i = 1, #b do
- j, t = i, n * (b[i] or 0)
- while true do
- t = (a[j] or 0) + t
- a[j] = t % base
- t = math.floor(t / base)
- if t == 0 then break end
- j = j + 1
- end
- end
- end
- local function s_to_t(self, s)
- local r, l = {}, #s
- for i = 1, l do r[i] = self.r_alpha_from[s:byte(l - i + 1)] end
- return r
- end
- local function t_to_s(self, t)
- local r, l = {}, #t
- for i = l, 1, -1 do r[l - i + 1] = self.alpha_to:byte(t[i] + 1) end
- return string.char(table.unpack(r))
- end
- local function get_power(self, n)
- return self.power[n] or next_power(
- get_power(self, n-1), self.base_from, self.base_to
- )
- end
- local function base_convert(self, t)
- local r = {}
- for i = 1, #t do
- add_times(r, t[i], get_power(self, i - 1), self.base_to)
- end
- return r
- end
- local function convert(self, s)
- return t_to_s(self, base_convert(self, s_to_t(self, s)))
- end
- local function validate(self, s)
- for i = 1, #s do
- if not self.r_alpha_from[s:byte(i)] then
- return false
- end
- end
- return true
- end
- local converter_mt = {
- __index = {convert = convert, validate = validate},
- __call = function(self, s) return self:convert(s) end,
- }
- function new_converter(alpha_from, alpha_to)
- local self = {
- alpha_to = alpha_to,
- base_from = #alpha_from,
- base_to = #alpha_to,
- }
- local v = {}
- for i = 1, #alpha_from do v[alpha_from:byte(i)] = i - 1 end
- self.r_alpha_from = v
- self.power = { [0] = {1} }
- return setmetatable(self, converter_mt)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement