megagrump
megagrump

Reputation: 128

Convert a 64 bits floating point number into two integer numbers < 2^32 and back in Lua 5.1

I want to convert a number (64 bit double precision) into two integer numbers (unsigned 32 bits) and back. Is that possible to do without precision loss? The 64 bit number should fit into two 32 bit numbers, I just can't figure out how to do it in Lua.

My experiments with the bitop library in LuaJIT did not result in anything useful. Is it possible to cast the number to unsigned long long and split that one up, in pure Lua code using the ffi API?

Maybe it's not possible without precision loss. What is a reasonable way to do it, even if I lose precision?

Upvotes: 1

Views: 925

Answers (2)

lhf
lhf

Reputation: 72352

You can extract the bytes of the IEEE 754 representation of a double using math.frexp and rebuild the number from the bytes using math.ldexp.

See packers.double and unpack_double.

Try also the simpler code at http://lua-users.org/lists/lua-l/2015-03/msg00159.html.

Upvotes: 1

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23757

Using LuaJIT:

local ffi = require"ffi"
local u = ffi.new"union{uint32_t i[2]; double d;}"
-- convert double into pair of int32
u.d = 1/3
print(("%x %x"):format(u.i[0], u.i[1]))  --> 55555555 3fd55555

Upvotes: 3

Related Questions