lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Reuben Thomas writes:

>function bxor (a,b)
>  local r = 0
>  for i = 0, 31 do
>    local x = a / 2 + b / 2
>    if x ~= floor (x) then
>      r = r + 2^i
>    end
>    a = floor (a / 2)
>    b = floor (b / 2)
>  end
>  return r
>end

On similar lines: I've somehow ended up using Lua to do CPU simulation, and
found it very useful to have functions to convert between integers and
arrays of bits.  Once you've got the bit arrays, it's very easy to implement
any boolean function.  Just as long as you don't care about speed.

function toBits( value, width )
	if width == nil then
		width = 8
	end
	local result = {}
	for i = 0, 7 do
		local newValue = floor( value/2 )
		if newValue*2 == value then
			result[i] = 0
		else
			result[i] = 1
		end
		value = newValue
	end
	return result
end

function fromBits( bits, width )
	if width == nil then
		width = 8
	end
	local result = 0
	for i = 7, 0, -1 do
		result = 2*result + bits[i]
	end
	return result
end

They're exact if your integers don't exceed the size of the mantissa (32
bits fit in a double with plenty of room to spare).
-Virus scanned and cleared ok