我正在尝试将字符串数据作为字节转换并写入文件。
我已经尝试过,但是我在 hexdump 中没有看到 00,而是在文件中看到了 0x30,它是字符 0 的十六进制值。
这是我写的:
local data = "000000010000000100000004000000080000000100000000"
for i=1,#data,2 do
file:write(tonumber(data:sub(i,i+1)))
end
io.close(file)
当我对文件进行 hexdump 时,我得到了这个:
0000000 30 30 30 31 30 30 30 31 30 30 30 34 30 30 30 38
0000010 30 30 30 31 30 30 30 30
0000018
预期是:
0000000 00 00 00 01 00 00 00 01 00 00 00 04 00 00 00 08
0000010 00 00 00 01 00 00 00 00
0000018
最佳答案
您想使用 string.char
以一种方式:
local data = "000000010000000100000004000000080000000100000000"
for i=1,#data,2 do
file:write(string.char(tonumber(data:sub(i,i+1), 16)))
end
io.close(file)
或另一个:
local data = string.char(0,0,0,1,0,0,0,1,0,0,0,4,0,0,0,8,0,0,0,1,0,0,0,0)
file:write(data)
io.close(file)
请注意,Lua 中的字符串可以包含您想要的任何字节,包括空字节。参见 Values and Types .
关于string - 将字符串转换为字节并在Lua中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57675315/