Advertisement
osmarks

BaseN

Feb 28th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.18 KB | None | 0 0
  1. -- https://github.com/oploadk/base2base for computercraft
  2.  
  3. local fmt = string.format
  4.  
  5. local function next_power(p, base_from, base_to)
  6.     local r, j, t = {}
  7.     for i = 1, #p do
  8.         j, t = i, p[i] * base_from
  9.         while true do
  10.             t = (r[j] or 0) + t
  11.             r[j] = t % base_to
  12.             t = math.floor(t / base_to)
  13.             if t == 0 then break end
  14.             j = j + 1
  15.         end
  16.     end
  17.     return r
  18. end
  19.  
  20. -- a = a + n * b
  21. local function add_times(a, n, b, base)
  22.     local j, t
  23.     for i = 1, #b do
  24.         j, t = i, n * (b[i] or 0)
  25.         while true do
  26.             t = (a[j] or 0) + t
  27.             a[j] = t % base
  28.             t = math.floor(t / base)
  29.             if t == 0 then break end
  30.             j = j + 1
  31.         end
  32.     end
  33. end
  34.  
  35. local function s_to_t(self, s)
  36.     local r, l = {}, #s
  37.     for i = 1, l do r[i] = self.r_alpha_from[s:byte(l - i + 1)] end
  38.     return r
  39. end
  40.  
  41. local function t_to_s(self, t)
  42.     local r, l = {}, #t
  43.     for i = l, 1, -1 do r[l - i + 1] = self.alpha_to:byte(t[i] + 1) end
  44.     return string.char(table.unpack(r))
  45. end
  46.  
  47. local function get_power(self, n)
  48.     return self.power[n] or next_power(
  49.         get_power(self, n-1), self.base_from, self.base_to
  50.     )
  51. end
  52.  
  53. local function base_convert(self, t)
  54.     local r = {}
  55.     for i = 1, #t do
  56.         add_times(r, t[i], get_power(self, i - 1), self.base_to)
  57.     end
  58.     return r
  59. end
  60.  
  61. local function convert(self, s)
  62.     return t_to_s(self, base_convert(self, s_to_t(self, s)))
  63. end
  64.  
  65. local function validate(self, s)
  66.     for i = 1, #s do
  67.         if not self.r_alpha_from[s:byte(i)] then
  68.             return false
  69.         end
  70.     end
  71.     return true
  72. end
  73.  
  74. local converter_mt = {
  75.     __index = {convert = convert, validate = validate},
  76.     __call = function(self, s) return self:convert(s) end,
  77. }
  78.  
  79. function new_converter(alpha_from, alpha_to)
  80.     local self = {
  81.         alpha_to = alpha_to,
  82.         base_from = #alpha_from,
  83.         base_to = #alpha_to,
  84.     }
  85.     local v = {}
  86.     for i = 1, #alpha_from do v[alpha_from:byte(i)] = i - 1 end
  87.     self.r_alpha_from = v
  88.     self.power = { [0] = {1} }
  89.     return setmetatable(self, converter_mt)
  90. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement