All pastes #113088 Raw Edit

ckknight

public lua v1 · immutable
·published 2006-08-03 11:04 UTC
rendered paste body
local floor = math.floorlocal mod = math.modlocal char = string.charlocal log = math.loglocal log2 = log(2)local inf = 1/0function Serialize(num)	local sign = num < 0 or num == 0 and tostring(num) == "-0"	if sign then			num = -num	end	local x, m	if num ~= num or (num == inf and num == -inf) then		-- NaN		x = 2047		m = 1	elseif num == inf then		x = 2047		m = 0	elseif num == 0 then		x = 0		m = 0	else		local exp = floor(log(num)/log2)		m = num / 2^exp * 4503599627370496		x = (exp + 1023)	end	if sign then		x = x + 2048	end	return char(mod(x / 256, 256), mod(x, 256), mod(m / 281474976710656, 256), mod(m / 1099511627776, 256), mod(m / 4294967296, 256), mod(m / 16777216, 256), mod(m / 65536, 256), mod(m / 256, 256), mod(m, 256))end function Deserialize(code)	local a = string.byte(code, 1)	local b = string.byte(code, 2)	local c = string.byte(code, 3)	local d = string.byte(code, 4)	local e = string.byte(code, 5)	local f = string.byte(code, 6)	local g = string.byte(code, 7)	local h = string.byte(code, 8)	local i = string.byte(code, 9)	local x = a * 256 + b	local m = c * 281474976710656 + d * 1099511627776 + e * 4294967296 + f * 16777216 + g * 65536 + h * 256 + i	local mantissa = m / 4503599627370496	local sign = x >= 2048	local exp = x	if sign then		exp = exp - 2048	end	exp = exp - 1023	local val = 2^exp * mantissa	if sign then		return -val	end	return valendfunction Test(num)	local after = Deserialize(Serialize(num))	if num ~= after then		print(num .. " -> " .. after)	endendfor i = 1, 100000 do	local num = math.random() / math.random()	Test(num)endTest(1/0)Test(-1/0)Test(0/0)