lua-users home
lua-l archive

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

> > You can implement XOR in pure Lua but it's very slow. Probably the easiest
> > way is to do it bit by bit, but maybe there's a clever trick to do it
> > faster with whole-word arithmetic.
> Slow isn't really an issue; I just need the ability to XOR in Lua.

I suggest asking Tom to add bitlib (it's tiny, and bitwise operations must 
be useful in tomsrtbt); short of that, just do the obvious thing: look at 
each bit in the two words one at a time:

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
    a = floor (a / 2)
    b = floor (b / 2)
  return r

(Unusually for a mailing list, this code has been tested :-)

I'll add this routine (and band and bor) to the Lua standard libraries
project, for those who have a similar problem.

-- | wit, n.  educated insolence (Aristotle)