randomdude999

Base64 for ComputerCraft

May 20th, 2016
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.39 KB | None | 0 0
  1. -- Base64 by randomdude999
  2. -- code mostly based on tomass1996's implementation
  3.  
  4. -- bitwise functions
  5. local function lsh(value,shift)
  6.         return (value*(2^shift)) % 256
  7. end
  8. local function rsh(value,shift)
  9.         return math.floor(value/2^shift) % 256
  10. end
  11. local function bit(x,b)
  12.         return (x % 2^b - x % 2^(b-1) > 0)
  13. end
  14. local function lor(x,y)
  15.         result = 0
  16.         for p=1,8 do result = result + (((bit(x,p) or bit(y,p)) == true) and 2^(p-1) or 0) end
  17.         return result
  18. end
  19.  
  20. --actual stuff
  21. local base64chars = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','-','_'}
  22. function encode(data)
  23.     local bytes = {}
  24.     local result = ""
  25.     for spos=0,data:len()-1,3 do
  26.         for b=1,3 do bytes[b] = data:sub(spos+b):byte() or 0 end
  27.                 result = string.format('%s%s%s%s%s',result,base64chars[rsh(bytes[1],2)+1],base64chars[lor(lsh((bytes[1] % 4),4), rsh(bytes[2],4))+1] or "=",((#data-spos) > 1) and base64chars[lor(lsh(bytes[2] % 16,2), rsh(bytes[3],6))+1] or "=",((#data-spos) > 2) and base64chars[(bytes[3] % 64)+1] or "=")
  28.     end
  29.     return result
  30. end
  31.  
  32.  
  33. local base64bytes = {['A']=0,['B']=1,['C']=2,['D']=3,['E']=4,['F']=5,['G']=6,['H']=7,['I']=8,['J']=9,['K']=10,['L']=11,['M']=12,['N']=13,['O']=14,['P']=15,['Q']=16,['R']=17,['S']=18,['T']=19,['U']=20,['V']=21,['W']=22,['X']=23,['Y']=24,['Z']=25,['a']=26,['b']=27,['c']=28,['d']=29,['e']=30,['f']=31,['g']=32,['h']=33,['i']=34,['j']=35,['k']=36,['l']=37,['m']=38,['n']=39,['o']=40,['p']=41,['q']=42,['r']=43,['s']=44,['t']=45,['u']=46,['v']=47,['w']=48,['x']=49,['y']=50,['z']=51,['0']=52,['1']=53,['2']=54,['3']=55,['4']=56,['5']=57,['6']=58,['7']=59,['8']=60,['9']=61,['-']=62,['_']=63,['=']=nil}
  34. function decode(data)
  35.         local chars = {}
  36.         local result=""
  37.         for dpos=0,data:len()-1,4 do
  38.                 for char=1,4 do chars[char] = base64bytes[(data:sub(dpos+char,dpos+char) or "=")] end
  39.                 result = string.format('%s%s%s%s',result,string.char(lor(lsh(chars[1],2), rsh(chars[2],4))),(chars[3] ~= nil) and string.char(lor(lsh(chars[2],4), rsh(chars[3],2))) or "",(chars[4] ~= nil) and string.char(lor(lsh(chars[3],6) % 192, (chars[4]))) or "")
  40.         end
  41.         return result
  42. end
Advertisement
Add Comment
Please, Sign In to add comment