Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing strings to binary in Lua

Tags:

string

binary

lua

I'm having issues writing strings to binary in Lua. There is an existing example and I tried modifying it. Take a look:

function StringToBinary()
  local file = io.open("file.bin", "wb")
  local t = {}
  local u = {}
  local str = "Hello World" 
  file:write("string len = " ..#str ..'\n')
  math.randomseed(os.time())
  for i=1, #str do
    t[i] =  string.byte(str[i])
    file:write(t[i].." ");   
  end  
  file:write("\n")
  for i=1, #str do 
    u[i] = math.random(0,255) 
    file:write(u[i].." ");
  end
  file:write("\n"..string.char(unpack(t)))
  file:write("\n"..string.char(unpack(u)))
  file:close()
end

file:write(t[i].." ") and file:write(u[i].." ") write both tables with integer value. However with my last two writes: unpack(t) displays the original text, while unpack(u) displays the binaries.

It's probably string.byte(str[i]) that is mistaken. What should I replace it with? Am I missing something?

like image 832
xacrilege Avatar asked May 12 '26 08:05

xacrilege


1 Answers

t[i] =  string.byte(str[i])

is wrong, it should be:

t[i] =  string.byte(str, i)
like image 134
Yu Hao Avatar answered May 14 '26 09:05

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!