xacrilege
xacrilege

Reputation: 31

Writing strings to binary in 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?

Upvotes: 3

Views: 5298

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

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

is wrong, it should be:

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

Upvotes: 4

Related Questions