urielsalis

Untitled

Apr 1st, 2013
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. --254 is end of line
  2. --255 is end of stream
  3. line = "back"
  4. function dec2Bin(dec2)
  5. dec = tonumber(dec2)
  6. dec=dec*2
  7. local bin=""
  8. for i=0,7 do
  9. bin=bin..tostring(math.ceil(math.floor(dec/2)%2))
  10. dec=math.floor(dec/2)
  11. end
  12. return string.reverse(bin)
  13. end
  14.  
  15. function bin2Dec(bin)
  16. return tonumber(bin, 2)
  17. end
  18. function toBinary(str)
  19. binary = ""
  20. for i=1, #str do
  21. local a = str:sub(i, i)
  22. if a == "\n" then
  23. b = dec2Bin(254)
  24. else
  25. local b = dec2Bin(string.byte(a))
  26. binary = binary..b
  27. end
  28. end
  29. return binary
  30. end
  31. function fromBinary(str)
  32. count = 0
  33. actualbit = ""
  34. text = ""
  35. print("Sending "..#str * 8.." bytes")
  36. for i=1, #str do
  37. count = count+1
  38. actualbit = actualbit..str:sub(i,i)
  39. if count==8 then
  40. if actualbit==dec2Bin(254) then
  41. text = text.."\n"
  42. else
  43. text = text..string.char(bin2Dec(actualbit))
  44. actualbit = ""
  45. count = 0
  46. end
  47. end
  48. end
  49. count = nil
  50. actualbit = nil
  51. return text
  52. end
  53. function send(filename)
  54. file = fs.open(filename, "r")
  55. local a = file.readAll()
  56. file.close()
  57. local b = toBinary(a)
  58. rs.setOutput(line, true)
  59. sleep(0)
  60. rs.setOutput(line, false)
  61. for i=1, #b do
  62. local c = b:sub(i, i)
  63. if c=="1" then
  64. rs.setOutput(line, true)
  65. sleep(0)
  66. rs.setOutput(line, false)
  67. else
  68. sleep(0)
  69. end
  70. end
  71. end
  72. function receive(filename)
  73. bin = ""
  74. actualbit = ""
  75. count = 0
  76. os.pullEvent("redstone")
  77. while true do
  78. sleep(0)
  79. count = count+1
  80. if rs.getInput(line) then
  81. actualbit = actualbit.."1"
  82. else
  83. actualbit = actualbit.."0"
  84. end
  85. if count==8 then
  86. if actualbit == dec2Bin(255) then break end
  87. bin = bin..actualbit
  88. actualbit = ""
  89. count = 0
  90. end
  91. end
  92. actualbit = nil
  93. count = nil
  94. text = fromBinary(bin)
  95. file = fs.open(filename, "w")
  96. file.write(text)
  97. file.close()
  98. end
  99. args = {...}
  100. if #args==2 then
  101. if args[1]=="-send" then
  102. send(args[2])
  103. else
  104. receive(args[2])
  105. end
  106. end
Advertisement
Add Comment
Please, Sign In to add comment