Bit 存储操作代码碎片

Lua 版本
--
返回0或1 function GetBit(value, index) return value >> index & 1 end -- bitValue取值 0或1,返回存储后数值 function SetBit(value, index, bitValue) local val = 1 << index return bitValue > 0 and (value | val) or (value & ~val) end

 基于上面,很快就有了下面两个高级方法

-- 返回0或1 , array = {number, number, number, ...}
function GetBitInArray(array, index)
    local x = math.floor(index / 32)
    local y = index % 32
    return GetBit(array[x + 1] or 0, y)
end

function SetBitInArray(array, index, bitValue)
    local x = math.floor(index / 32)
    local y = index % 32
    local cnt = #array
    if cnt < x + 1 then
        for i = cnt, x do
            table.insert(array, 0)
        end
    array[x + 1] = SetBit(array[x + 1], y, bitValue)
end

 以上方法的用处;

可以用来标记比如一串的成就,哪些达成,哪些没有达成。任务的完成情况,宝箱的领取情况等。

比如数字1 就可标注32个位置的信息 0000 0000 0000 0000 0000 0000 0000 0001

posted @ 2020-04-09 11:27  大表哥的笔记  阅读(253)  评论(1编辑  收藏  举报