lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> From: Jose Marin [mailto:jose_marin2@yahoo.com.br] 

> How do I deal with binary files in Lua?

It's not hard to write a set of functions for reading and writing integers
in your platform's native format.  Here's mine (for a 32 bit little-endian
machine):

function readbyte( file )
	local str = file:read( 1 )
	return string.byte( str, 1 )
end

function writebyte( file, value )
	file:write( string.char(value) )
end

function readshort( file )
	local str = file:read( 2 )
	return string.byte( str, 1 ) + 256*string.byte( str, 2 )
end

function writeshort( file, value )
	local h = math.floor(value / 256)
	local l = value - 256*h
	writebyte( file, l )
	writebyte( file, h )
end

function readint( file )
	local str = file:read( 4 )
	return string.byte( str, 1 ) + 256*string.byte( str, 2 ) + 
		256*256*string.byte( str, 3 ) + 256*256*256*string.byte(
str, 4 )
end

function writeint( file, value )
	local h = math.floor(value / 65536)
	local l = value - 65536*h
	writeshort( file, l )
	writeshort( file, h )
end

floating point is a little trickier, but nothing impossible.  This one reads
a subset of IEEE single precision (no infinities or NANs, and I've never
tested denormalised):

function readfloat( file )
	local int = readint( file )
	local f = 1 + mod( int, 128*256*256 )/(128*256*256)
	local e = math.floor( int/(128*256*256) )
	local s
	if e >= 256 then
		e = e - 256
		s = -1
	else
		s = 1
	end
	e = e - 127
	return s * f * 2^e
end

I haven't written writefloat because so far I haven't needed it.

> Also, is possible to write to a file, in Lua, that a
> C++ program could read as a struct?

I do it all the time, but you have to be very careful.  In particular, you
need to know if and how the compiler adds alignment padding.  In your
example

> struct{
>   char name[STR_MAX];
>   int n;
>   float f;
> }struct_aux;

I'd explicitly add padding after the char array, if STR_MAX isn't a multiple
of 4 (the machine I build data files for has 32 bit int and float, and 8 bit
char).

Don't expect this sort of thing to be remotely portable.  I've had personal
experience of CPU/compiler combinations with 8 or 16 bit chars, 16 or 32 bit
ints, and 32 or 64 bit long ints.