Advertisement
InTesting

Fun base system converter

Jun 26th, 2021 (edited)
1,056
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.39 KB | None | 0 0
  1. -- done in LuaU, expect compound assignments and exclusive keywords
  2.  
  3.  
  4.  
  5. function FACT_NumToStrFromBase(charstable)
  6.     local base = #charstable
  7.     return function(num)
  8.         local res = ''
  9.        
  10.         local its = 1 + math.max(0,math.floor(math.log(num,base)))
  11.        
  12.         for i=its,1,-1  do -- going down number places
  13.             local factor = base ^ (i - 1)
  14.            
  15.             local nk = base - 1
  16.            
  17.             for k=base,1,-1 do -- going down the base to 1
  18.                 local num2 = factor * (k - 1)
  19.                
  20.                 if num - num2 < 0 then continue end
  21.                
  22.                 nk = k
  23.                 num -= num2
  24.                
  25.                 break
  26.             end
  27.            
  28.             res ..= charstable[nk]
  29.         end
  30.        
  31.         return res
  32.     end
  33. end
  34.  
  35. function FACT_StrToNumFromBase(charstable)
  36.     local base = #charstable
  37.     local FlippedCharacters = {}
  38.     for i,v in next,charstable do FlippedCharacters[tostring(v)] = i end
  39.    
  40.     return function(str)
  41.        
  42.         local res = 0
  43.        
  44.         for a=1,#str do -- iterate each letter
  45.             local letter = str:sub(a,a)
  46.            
  47.             local num = (FlippedCharacters[letter] - 1) * base ^ (#str - a)
  48.             res += num
  49.         end
  50.        
  51.         return res
  52.     end
  53. end
  54.  
  55. local numtobin = FACT_NumToStrFromBase(string.split('01',''))
  56. local numtohex = FACT_NumToStrFromBase(string.split('0123456789abcdef',''))
  57.  
  58. local bintonum = FACT_StrToNumFromBase((string.split('01','')))
  59. local hextonum = FACT_StrToNumFromBase(string.split('0123456789abcdef',''))
  60.  
  61.  
  62. for a=0,32 do
  63.     local b = numtobin(a)
  64.    
  65.     print(a,b,bintonum(b))
  66. end
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement