7

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.

Merni
  • 2,842
  • 5
  • 36
  • 42
  • You want to write `10000011111101110001010` or `34333234323334`? – hjpotter92 Jun 30 '14 at 09:04
  • I want to write 10000011111101110001010, but not in string format, I want to write 4 bytes, the size of an integer. – Merni Jun 30 '14 at 09:14
  • I don't think Lua has built in support for this. Your best bet would be to add some `C` functions to turn numbers into the appropriate strings. – Mankarse Jun 30 '14 at 10:25
  • But if I have over 100k values it will take a lot of space. And Im in corona so I cant call any c functions directly. – Merni Jun 30 '14 at 11:03
  • Related: [Reading/Writing Binary files](http://stackoverflow.com/q/17462099/183120) – legends2k Dec 08 '14 at 06:19

2 Answers2

6

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

local struct = require('struct')
out:write(struct.pack('i4',0x123432))
legends2k
  • 31,634
  • 25
  • 118
  • 222
lipp
  • 5,586
  • 1
  • 21
  • 32
3

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.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • would you read four bytes at a time or would you read everything and then later split it up in 4 bytes? – Merni Jun 30 '14 at 13:16
  • one more question:), if a read one byte at a time it works, if I read 4 bytes, local bytes = f:read(4) local firstByte = string.byte(bytes), how do I get the rest of the bytes, I cant really divide by 256 because its not a pointer to the first position, just a byte – Merni Jun 30 '14 at 13:28
  • @Merni, ask a separate question or edit this one with your efforts for reading. – lhf Jun 30 '14 at 14:11
  • Since Lua 5.3 you can use [string.pack](http://www.lua.org/manual/5.3/manual.html#pdf-string.pack) to write values in binary. – lhf Oct 20 '16 at 10:06