Lua: bitwise xor for Lua < 5.2


Lua: bitwise xor for Lua < 5.2

local math = require("math")

-- bitwise xor 
local function bxor (a,b)

	local r = 0
	local i = 0
	while true do
		local x = a / 2 + b / 2
		if x ~= math.floor (x) then
			r = r + 2^i
		end
		a = math.floor (a / 2)
		b = math.floor (b / 2) 

		if a==0 and b==0 then break end
		i = i + 1
	end
	return r

end

Example:

local x = bxor(0b1000,0b0100)

print(x) --12 = 0b1100

Leave a Reply