[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
**Subject**: **RE: Bitwise XOR in Lua?**
**From**: John Mckenna <jmckenna@...>
**Date**: Mon, 9 Sep 2002 09:38:21 +0100

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