Dragon53535

String to Binary

Jul 26th, 2014
1,161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.65 KB | None | 0 0
  1. local function numberString(number)
  2.   local s = ""
  3.   repeat
  4.     local remainder = number % 2
  5.     s = remainder..s
  6.     number = (number-remainder)/2
  7.   until number==0
  8.   return s
  9. end
  10. function fromBinary(str)
  11.   if #str % 8 ~= 0 then
  12.     error("Malformed Binary Sequence",2)
  13.   end
  14.   local result = ""
  15.   for i = 1, #str, 8 do
  16.    result = result..string.char(tonumber(str:sub(i,i+7),2))
  17.   end
  18.   return result
  19. end
  20. function toBinary(str)
  21.   if #str > 0 then
  22.     local result = ""
  23.     for a = 1, #str do
  24.       result = result..string.format("%08d",numberString(string.byte(string.sub(str,a,a))))
  25.     end
  26.     return result
  27.   else return nil
  28.   end
  29. end
Advertisement
Add Comment
Please, Sign In to add comment