gpt4 book ai didi

lua - 读/写二进制文件

转载 作者:行者123 更新时间:2023-12-04 13:45:45 27 4
gpt4 key购买 nike

我只是想从二进制文件中读/写。我一直在关注 this教程,它的工作原理......除了它似乎正在将内容写入 txt 文件。我在测试的时候把文件命名为test.bin,但是记事本可以打开并正常显示,所以我认为它实际上不是一个二进制文件。我已经告诉它它是一个带有“wb”和“rb”的二进制文件,对吗?

if arg[1] == "write" then
local output = assert(io.open(arg[2], "wb"))

output:write(arg[3]) --3rd argument is written to the file.

assert(output:close())
elseif arg[1] == "read" then
local input = assert(io.open(arg[2], "rb"))

print(input:read(1)) --Should read one byte, not one char/int. Right?
end

最佳答案

如果您只将 ASCII 字符写入文件,则可以在记事本或任何其他文本编辑器中打开它就好了:

local out = io.open("file.bin", "wb")
local str = string.char(72,101,108,108,111,10) -- "Hello\n"
out:write(str)
out:close()

生成的文件将包含:
Hello

另一方面,如果你写真正的二进制数据(例如随机字节),你会得到垃圾:
local out = io.open("file.bin", "wb")
local t = {}
for i=1,1000 do t[i] = math.random(0,255) end
local str = string.char(unpack(t))
out:write(str)
out:close()

这类似于您看到的那些视频游戏保存文件。

如果您仍然不明白,请尝试将所有可能的八位字节写入文件:
local out = io.open("file.bin", "wb")
local t = {}
for i=0,255 do t[i+1] = i end
local str = string.char(unpack(t))
out:write(str)
out:close()

然后用十六进制编辑器打开它(这里我在Mac OS上使用了Hex Fiend)查看对应关系:

hex

在这里,左边是十六进制的字节,右边是它们的文本表示。我选择了大写的 H,正如您在左侧看到的那样,它对应于 0x48。 0x48 是 4*16 + 8 = 72 以 10 为基数(查看屏幕截图的底部栏,它告诉您这一点)。

现在看看我的第一个代码示例,猜猜小写 e 的代码是什么......

最后查看屏幕截图的最后 4 行(字节 128 到 255)。这就是你看到的垃圾。

关于lua - 读/写二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17462099/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com