Advertisement
ilovepants

Binary to Text Conversion

Jun 23rd, 2014
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.81 KB | None | 0 0
  1. local functions = {}
  2.  
  3. functions.decimalToBinary = function(n)
  4.     local b = {}
  5.    
  6.     for i = 7, 0, -1 do
  7.         if n/2^i >= 1 then
  8.             b[8 - i] = 1
  9.             n = n - 2^i
  10.         else
  11.             b[8 - i] = 0
  12.         end
  13.     end
  14.    
  15.     return table.concat(b)
  16. end
  17.  
  18. functions.binaryToASCII = function(b)
  19.     local ASCII = 0
  20.    
  21.     for i = 1, 8 do
  22.         ASCII = ASCII + tonumber(b:sub(i, i)) * 2^(8 - i)
  23.     end
  24.    
  25.     return ASCII
  26. end
  27.  
  28. functions.textToBinary = function(s)
  29.     local b = {}
  30.     s = tostring(s)
  31.    
  32.     for i = 1, s:len() do
  33.         b[i] = functions.decimalToBinary(s:sub(i, i):byte())
  34.     end
  35.    
  36.     return table.concat(b)
  37. end
  38.  
  39. functions.binaryToText = function(b)
  40.     local s = {}
  41.     b = tostring(b)
  42.    
  43.     for i = 1, b:len(), 8 do
  44.         s[1 + ((i - 1)/8)] = string.char(functions.binaryToASCII(b:sub(i, i + 8)))
  45.     end
  46.    
  47.     return table.concat(s)
  48. end
  49.  
  50. return functions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement