require "bit"
local function setBitFlags(input, stand, bitValue)
-- 0-7 -> 1 2 4 8 16 32 64 128
local mask = 2 ^ (stand - 1)
return bitValue == 1 and bit.bor(input, mask) or bit.bxor(input, mask)
end
local function getBitFlag(input, stand)
local mask = 2 ^ (stand - 1)
return bit.band(input, mask) == mask
end
-- and操作
-- 00000001 1
--[[
255 11111111
129 10000000
]]
local i = 129
print("bxor : ", bit.bxor(i, 128)) -- 置0
print("bxor : ", bit.bxor(i, 128))
i = 129
print("bnot : ", bit.bnot(i, 128))
print("bnot : ", bit.bnot(i, 128))
i = 128
print("bor : ", bit.bor(i, 128)) -- 置1
print("bor : ", bit.bor(i, 2))
local b = 255
local stand = 2
for i = 1, 8 do
b = setBitFlags(b, i, 0)
print(b)
end
local input = math.random(0, 255)
local outPut = {}
for i = 1, 8 do
table.insert(outPut, 1, getBitFlag(input, i) and 1 or 0 )
end
print(input, unpack(outPut))
do return end
在Lua下执行位运算
最新推荐文章于 2024-03-07 09:51:52 发布