All pastes #112858 Raw Edit

ckknight

public text v1 · immutable
·published 2006-08-03 08:19 UTC
rendered paste body
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

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