[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: opening a file in binary mode
- From: Edgar Toernig <froese@...>
- Date: Wed, 21 Mar 2001 05:03:54 +0100
> >In any case, how do I open a file in binary and write binary data to it?
> >(I don''t want my numbers converted to strings, as that's what seems to
> >be happening)
And in what flavor do you want your numbers written? Bytes? Words? Long
words? Floats? Doubles? In what endian (little/big) or format (ieee floats,
BCD, ...). It's really not that easy. Standard Lua only supports simple
bytes via strchar() or format("%c").
> For numbers with fractional part, it's harder, but you may get by
> by using frexp. You might prefer to write a simple library that does this for
> you. Something like this (untested!):
>
> static tobinary(lua_State* L)
> {
> if arg is number then
> void* u=lua_newuserdata(L,sizeof(double));
> double x=lua_tonumber(L,1));
> memcpy(u,&x,sizeof(x));
> else if arg is string
> ; /* do nothing */
> return 1;
> }
>
> and export this to Lua. Then you'd simply do write(tobinary(x)) in Lua.
Didn't test this myself but how should `write' know how to emit userdata???
Maybe you meant something like this (untested too ;-):
static tobinary(lua_State* L)
{
double x = luaL_check_number(L, 1);
lua_pushlstring(L, (const char *)&x, sizeof(x));
return 1;
}
This converts a number to a binary string that holds the number in the
host's double representation.
Ciao, ET.