3

我在 Lua 中将字符串写入二进制文件时遇到问题。有一个现有的示例,我尝试对其进行修改。看一看:

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].." ")file:write(u[i].." ")用整数值写入两个表。但是,在我最后两次写入时:unpack(t)显示原始文本,同时unpack(u)显示二进制文件。

这可能string.byte(str[i])是错误的。我应该用什么代替它?我错过了什么吗?

4

1 回答 1

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

错了,应该是:

t[i] =  string.byte(str, i)
于 2013-10-31T04:40:26.993 回答