Advertisement
Snusmumriken

little byte lib

Jun 14th, 2017
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.93 KB | None | 0 0
  1. local byte = {}
  2. function byte.split(str, a, b)
  3.     local insert = table.insert
  4.     if type(a) == 'table' then
  5.         local t = {}
  6.         local cursor = 0
  7.         for i = 1, #a do
  8.             insert(t, str:sub(cursor+1, cursor+a[i]))
  9.             cursor = cursor + #(t[#t])
  10.         end
  11.         return b and unpack(t) or t
  12.     end
  13.     a, b = a or 0, b or 1
  14.     return str:sub(a+1, a+b)
  15. end
  16.  
  17. local max_int = 2^8
  18. function byte.encode(num, len)
  19.     local insert, char = table.insert, string.char
  20.     if len and num > max_int^len - 1 then
  21.         error('Encode too big number: %d, max is %d', num, max^len)
  22.     end
  23.     local t={}
  24.     while num > 0 do
  25.         local rest = num % 255
  26.         insert(t, char(rest))
  27.         num = (num - rest) / 255
  28.     end
  29.     if len and #t < len then insert(t, ('\0'):rep(len - #t)) end
  30.     return table.concat(t)
  31. end
  32.  
  33. function byte.decode(c)
  34.     local insert = table.insert
  35.     local n = 0
  36.     c = c:reverse()
  37.     for j = 1, #c do
  38.         n = n + c:sub(j, j):byte()*255^(#c-j)
  39.     end
  40.     return n
  41. end
  42.  
  43. return byte
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement