Advertisement
Guest User

Binary Work Around

a guest
Aug 3rd, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.12 KB | None | 0 0
  1. local fs = require "filesystem"
  2. local string = require "string"
  3.  
  4. local testDensity = {}
  5. local j = 0
  6. for i=0,255 do
  7.     testDensity[i] = math.floor(math.random()*3)
  8.    
  9. end
  10.  
  11. local number1 = 0
  12. local number2 = 0
  13. local number3 = 0
  14. local number4 = 0
  15. --convert a passed number to base 4
  16. local function convToFour(num)
  17.     number4 = math.floor(num)%4
  18.     number3 = (math.floor(num/4))%4
  19.     number2 = (math.floor(num/16))%4
  20.     number1 = (math.floor(num/64))%4
  21. end
  22. --convert a passed number to base 10 from base 4, numbers must be in range of 0-3 for all places
  23. local function convToTen(num)
  24.     local bTenNum1 = math.floor(num/1000)
  25.     local bTenNum2 = math.floor((num-(bTenNum1*1000))/100)
  26.     local bTenNum3 = math.floor((num-bTenNum1*1000-bTenNum2*100)/10)
  27.     local bTenNum4 = math.floor(num-bTenNum1*1000-bTenNum2*100-bTenNum3*10)
  28.     local bTenNum11 = bTenNum1*4^3
  29.     local bTenNum22 = bTenNum2*4^2
  30.     local bTenNum33 = bTenNum3*4^1
  31.     local bTenNum44 = bTenNum4*4^0
  32.     return(math.floor(bTenNum11+bTenNum22+bTenNum33+bTenNum44))
  33. end
  34.  
  35. local str = ""
  36. for i=0,63 do
  37. local compressedNum = 0
  38. --turns 4 table values into a fake base 4 number that the convToTen can work with
  39. compressedNum = testDensity[i*4] * 1000
  40. compressedNum = compressedNum + testDensity[i*4+1] * 100
  41. compressedNum = compressedNum + testDensity[i*4+2] * 10
  42. compressedNum = compressedNum + testDensity[i*4+3]
  43. --then uses that number to write a character assosiated with it
  44. str = str..string.char(convToTen(compressedNum))
  45. end
  46.  
  47. print(str)
  48. print(string.len(str))
  49. local file = io.open("testBinaryFile", "w")
  50. file:write(str)
  51. io.close(file)
  52.  
  53. str = ""
  54. --tests to make sure it can write and read correctly
  55. local file = io.open("testBinaryFile", "r")
  56. str = file:read("*all")
  57. io.close(file)
  58.  
  59. local recompiledString = ""
  60. for i = 1,64 do
  61.  
  62.     convToFour(string.byte(string.sub(str,i,i)))
  63.     recompiledString = recompiledString..tostring(number1)
  64.     recompiledString = recompiledString..tostring(number2)
  65.     recompiledString = recompiledString..tostring(number3)
  66.     recompiledString = recompiledString..tostring(number4)
  67. end
  68.  
  69. print(testDensity[0]..table.concat(testDensity))
  70. print(recompiledString)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement