2

I am playing Feed The Beast and would like to create a network. I can already send binary codes from one computer to another. The method to get a binary code out of a string is the following:

function toBinString(s)
  bytes = {string.byte(s,i,string.len(s))}
  binary = ""

  for i,number in ipairs(bytes) do
    c = 0

    while(number>0) do
      binary = (number%2)..binary
      number = number - (number%2)
      number = number/2
      c = c+1
    end

    while(c<8) do
      binary = "0"..binary
      c = c+1
    end
  end

  return binary
end

function toBin(s)
  binary = toBinString(s)    
  ret = {}
  c = 1

  for i=1,string.len(binary) do
    char = string.sub(binary,i,i)

    if(tonumber(char)==0) then
      ret[c] = 0
      c = c+1
    elseif(tonumber(char)==1) then
      ret[c] = 1
      c = c+1
    elseif(tonumber(char)) then
      print("Error: expected \'0\' or \'1\' but got \'",char,"\'.")
    end
  end

  return ret
end

How can I get the string that was used in string.byte(...)?

1 Answer 1

2

Here is one possibility:

function toBinAndBack(s)
  local bin = toBin(s)
  local r = {}
  for i=1,#bin,8 do
    local n = 0
    for j=0,7 do
      n = n + (2^(7-j)) * bin[i+j]
    end
    r[#r+1] = n
  end
  return string.char(unpack(r)):reverse()
end

The reverse at the end is needed because you encode the strings in reverse in toBinString. Also, I had to replace this line: bytes = {string.byte(s,i,string.len(s))} by bytes = {string.byte(s,1,-1)} to make your code work.

Note that using unpack() limits the size of the string that can be decoded. If you want to decode arbitrarily long strings, you can replace the last line (return string.char(unpack(r)):reverse()) by this:

for i=1,#r do
  r[i] = string.char(r[i])
end
return table.concat(r):reverse()
Sign up to request clarification or add additional context in comments.

3 Comments

about the bytes = ... thing: it worked for me (in-game) so I had no problems :D Anyway, I am going to use your code :) Thanks a lot.
In bytes = ... the string.len(s) is probably OK, but i has never been defined before. It must come from some other part of your code I guess :)
Could be, yes. I think that Ctrl+C was the cause of that i being there :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.