Posted By

ukpyr on 03/13/09


Tagged


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

CobaltHex
Tyster


str2base64


 / Published in: Lua
 

  1. --- Returns BASE64 representation of str
  2. function str2base64(str)
  3. local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  4. local s64 = ''
  5.  
  6. while #str > 0 do -- iterate through string
  7. local bytes_num = 0 -- number of shifted bytes
  8. local buf = 0 -- input buffer
  9. for byte_cnt=1,3 do
  10. buf = (buf * 256)
  11. if #str > 0 then -- if string not empty, shift 1st byte to buf
  12. buf = buf + string.byte(str, 1, 1)
  13. str = string.sub(str, 2)
  14. bytes_num = bytes_num + 1
  15. end
  16. end
  17. for group_cnt=1,(bytes_num+1) do
  18. b64char = math.fmod(math.floor(buf/262144), 64) + 1
  19. s64 = s64 .. string.sub(b64chars, b64char, b64char)
  20. buf = buf * 64
  21. end
  22. for fill_cnt=1,(3-bytes_num) do
  23. s64 = s64 .. '='
  24. end
  25. end
  26.  
  27. return s64
  28. end

Report this snippet  

You need to login to post a comment.