2012-07-24 03:11:53 +12:00
|
|
|
Bit = {}
|
|
|
|
|
|
2022-08-17 12:51:56 -03:00
|
|
|
function Bit.bit(p)
|
2025-04-04 12:40:37 -04:00
|
|
|
return 2 ^ (p - 1)
|
2022-08-17 12:51:56 -03:00
|
|
|
end
|
2012-07-24 03:11:53 +12:00
|
|
|
|
2022-08-17 12:51:56 -03:00
|
|
|
function Bit.hasBit(x, p)
|
|
|
|
|
return x % (p + p) >= p
|
|
|
|
|
end
|
2012-07-24 03:11:53 +12:00
|
|
|
|
2022-08-17 12:51:56 -03:00
|
|
|
function Bit.setbit(x, p)
|
|
|
|
|
return Bit.hasBit(x, p) and x or x + p
|
|
|
|
|
end
|
2012-07-24 03:11:53 +12:00
|
|
|
|
2022-08-17 12:51:56 -03:00
|
|
|
function Bit.clearbit(x, p)
|
|
|
|
|
return Bit.hasBit(x, p) and x - p or x
|
2025-10-19 12:35:09 -03:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
function Bit.bxor(a, b)
|
|
|
|
|
local result = 0
|
|
|
|
|
local bitVal = 1
|
|
|
|
|
while a > 0 and b > 0 do
|
|
|
|
|
local aMod = a % 2
|
|
|
|
|
local bMod = b % 2
|
|
|
|
|
if aMod ~= bMod then
|
|
|
|
|
result = result + bitVal
|
|
|
|
|
end
|
|
|
|
|
a = math.floor(a * 0.5)
|
|
|
|
|
b = math.floor(b * 0.5)
|
|
|
|
|
bitVal = bitVal * 2
|
|
|
|
|
end
|
|
|
|
|
result = result + (a + b) * bitVal
|
|
|
|
|
return result
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
function Bit.band(a, b)
|
|
|
|
|
local result = 0
|
|
|
|
|
local bitVal = 1
|
|
|
|
|
while a > 0 and b > 0 do
|
|
|
|
|
local aMod = a % 2
|
|
|
|
|
local bMod = b % 2
|
|
|
|
|
if aMod == 1 and bMod == 1 then
|
|
|
|
|
result = result + bitVal
|
|
|
|
|
end
|
|
|
|
|
a = math.floor(a * 0.5)
|
|
|
|
|
b = math.floor(b * 0.5)
|
|
|
|
|
bitVal = bitVal * 2
|
|
|
|
|
end
|
|
|
|
|
return result
|
2024-11-29 14:12:47 -03:00
|
|
|
end
|