Write numbers to a file in lua in binary format

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:write(i)

I am just writing the number as a string to the file. How do I write the correct bytes for the number to file. And how can I later read from it.

Answers


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.


You could use lua struct for more fine-grained control over binary conversion.

local struct = require('struct')
out:write(struct.pack('i4',0x123432))

Need Your Help

Google Currents like page-by-page reading style

android android-layout android-viewpager android-textview adjustable

I'm learning how to implement one-page reading style, like in Google Currents, for my app.

Stream lookup in PENTAHO Data Integration

pentaho kettle

Is it possible to get multiple result rows after evaluating a stream lookup step in Pentaho Data integration ? I have been trying this thing using a excel input file. But the result set always cont...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.