Write numbers to a file in lua in binary format

前端 未结 2 1499
我寻月下人不归
我寻月下人不归 2021-01-18 07:32

I have a big array with numbers I would like to write to a file.

But if I do this:

local out = io.open(\"file.bin\", \"wb\")
local i = 4324234
out:wr         


        
2条回答
  •  粉色の甜心
    2021-01-18 08:07

    Try this

    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)
    

    and also this

    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))
    

    These work for 32-bit integers and output the most significant byte first. Adapt as needed.

提交回复
热议问题