以二进制格式将数字写入lua文件

Mer*_*rni 7 io lua binaryfiles

我有一个很大的数组,我想写一个文件.

但如果我这样做:

local out = io.open("file.bin", "wb")
local i = 4324234
out:write(i)
Run Code Online (Sandbox Code Playgroud)

我只是将数字作为字符串写入文件.如何为要归档的数字写入正确的字节.我怎么能在以后阅读它.

lip*_*ipp 6

您可以使用lua结构对二进制转换进行更细粒度的控制.

local struct = require('struct')
out:write(struct.pack('i4',0x123432))
Run Code Online (Sandbox Code Playgroud)


lhf*_*lhf 3

尝试这个

function writebytes(f,x)
    local b4=string.char(x%256) x=(x-x%256)/256
    local b3=string.char(x%256) x=(x-x%256)/256
    local b2=string.char(x%256) x=(x-x%256)/256
    local b1=string.char(x%256) x=(x-x%256)/256
    f:write(b1,b2,b3,b4)
end

writebytes(out,i)
Run Code Online (Sandbox Code Playgroud)

还有这个

function bytes(x)
    local b4=x%256  x=(x-x%256)/256
    local b3=x%256  x=(x-x%256)/256
    local b2=x%256  x=(x-x%256)/256
    local b1=x%256  x=(x-x%256)/256
    return string.char(b1,b2,b3,b4)
end

out:write(bytes(0x10203040))
Run Code Online (Sandbox Code Playgroud)

它们适用于 32 位整数并首先输出最高有效字节。根据需要进行调整。