Advertisement
DropSquad

Binary Converter Module (Lua)

Sep 1st, 2015
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.14 KB | None | 0 0
  1. -- Roblox (JimmyChance):
  2.  
  3. local module = {}
  4.  
  5. module.toByte = function(v)
  6.     if type(v) == "number" then return tostring(v) end
  7.     return v:gsub(".", function(t) return " " .. t:byte() end):gsub("^%s*", "")
  8. end
  9.  
  10. module.toChar = function(v)
  11.     if type(v) == "number" then return v end
  12.     return (" " .. v):gsub("(%s*)(%d+)", function(_, char)
  13.         return char:char()
  14.     end)
  15. end
  16.  
  17. module.toDecimal = function(v)
  18.     return tostring(v):gsub("%d+", function(bin)
  19.         local returned = 0
  20.         for i = 1, #bin do
  21.             local place = 2^(i - 1)
  22.             returned = returned + place * tonumber(bin:sub(-i, -i))
  23.         end
  24.         return returned
  25.     end)
  26. end
  27.  
  28. module.toBinary = function(v)
  29.     return module.toByte(v):gsub("%d+", function(char)
  30.         local number = tonumber(char)
  31.         local returned = ""
  32.         while math.floor(number/2) > 0 do
  33.             local remainder = number % 2
  34.             returned = returned .. remainder
  35.             number = math.floor(number/2)
  36.         end returned = returned .. number
  37.         return ("%08d"):format(tonumber(returned:reverse()))
  38.     end)
  39. end
  40.  
  41. _G.module = module
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement