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.
Binary format means that the sign (positive or negative) is in the leftmost bit of the field and the numeric value is in the remaining bits of the field. Positive numbers have a zero in the sign bit; negative numbers have a one in the sign bit and are in twos complement form.
A binary file is a file whose content is in a binary format consisting of a series of sequential bytes, each of which is eight bits in length. The content must be interpreted by a program or a hardware processor that understands in advance exactly how that content is formatted and how to read the data.
Binary data can be stored in a table using the data type bytea or by using the Large Object feature which stores the binary data in a separate table in a special format and refers to that table by storing a value of type oid in your table.
In Unix, there is no difference between binary files and text files. But in some systems, notably Windows, binary files must be opened with a special flag. To handle such binary files, you must use io.open , with the letter ` b ´ in the mode string. Binary data in Lua are handled similarly to text.
The operations such as reading the data from the file, writing the data to a file and appending the data to the existing data in a file can be performed in Lua using I/O library. The first step to perform any operation on the file is to open the file.
I/O library is used for reading and manipulating files in Lua. There are two kinds of file operations in Lua namely implicit file descriptors and explicit file descriptors.
A string in Lua may contain any bytes and almost all functions in the libraries can handle arbitrary bytes. (You can even do pattern matching over binary data, as long as the pattern does not contain a zero byte.
You could use lua struct for more fine-grained control over binary conversion.
local struct = require('struct')
out:write(struct.pack('i4',0x123432))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With