All pastes #112872 Raw Edit

ckknight

public text v1 · immutable
·published 2006-08-03 08:40 UTC
rendered paste body
local function simpletobin(num)
	local s = ""
	while num ~= 0 do
		local bit = math.mod(num, 2)
		num = math.floor(num / 2)
		s = bit .. s
	end
	while string.len(s) < 64 do
		s = "0" .. s
	end
	return s
end

local floor = math.floor

function tobin(num)
	local sign = false
	if num < 0 then
		sign = true
		num = -num
	end
	local whole = floor(num)
	local part = num - whole
	local x = 0
	local n = 0
	local first = true
	while true do
		local q = whole / 2
		whole = floor(q)
		if whole == 0 then
			break
		end
		local bit
		if whole ~= q then
			x = x + 2^n
		end
		n = n + 1
	end
	local m = n + 1023
	while part ~= 0 do
		part = 2 * part
		local b = floor(part)
		x = x * 2 + b
		n = n + 1
		part = part - b
	end
	x = x * 2^(52 - n)
	n = 52
	while m ~= 0 do
		local q = m / 2
		m = floor(q)
		if m ~= q then
			x = x + 2^n
		end
		n = n + 1
	end
	if sign then
		x = x + 2^63
	end
	return simpletobin(x)
end