i playing feed beast , create network. can send binary codes 1 computer another. method binary code out of string following:
function tobinstring(s) bytes = {string.byte(s,i,string.len(s))} binary = "" i,number in ipairs(bytes) c = 0 while(number>0) binary = (number%2)..binary number = number - (number%2) number = number/2 c = c+1 end while(c<8) binary = "0"..binary c = c+1 end end return binary end function tobin(s) binary = tobinstring(s) ret = {} c = 1 i=1,string.len(binary) char = string.sub(binary,i,i) if(tonumber(char)==0) ret[c] = 0 c = c+1 elseif(tonumber(char)==1) ret[c] = 1 c = c+1 elseif(tonumber(char)) print("error: expected \'0\' or \'1\' got \'",char,"\'.") end end return ret end
how can string used in string.byte(...)
?
here 1 possibility:
function tobinandback(s) local bin = tobin(s) local r = {} i=1,#bin,8 local n = 0 j=0,7 n = n + (2^(7-j)) * bin[i+j] end r[#r+1] = n end return string.char(unpack(r)):reverse() end
the reverse
@ end needed because encode strings in reverse in tobinstring
. also, had replace line: bytes = {string.byte(s,i,string.len(s))}
bytes = {string.byte(s,1,-1)}
make code work.
note using unpack()
limits size of string can decoded. if want decode arbitrarily long strings, can replace last line (return string.char(unpack(r)):reverse()
) this:
for i=1,#r r[i] = string.char(r[i]) end return table.concat(r):reverse()
Comments
Post a Comment