【问题标题】:Can anybody please tell me how to set or reset a bit in lua..?谁能告诉我如何在lua中设置或重置一点..?
【发布时间】:2021-02-24 08:30:44
【问题描述】:

我想对数字中的特定位执行设置和重置。由于我使用的是 lua 5.1,我无法使用 API 和移位运算符,所以它变得越来越复杂,所以请帮我找到这个

【问题讨论】:

    标签: lua lua-table esp32 nodemcu nodemcu-build


    【解决方案1】:

    bit 库随固件一起提供。

    阅读文档:https://nodemcu.readthedocs.io/en/release/modules/bit/

    【讨论】:

    • OP 显然使用了 ESP32。因此,链接应该指向dev-esp32 分支(在这种特殊情况下,模块是相同的)。
    【解决方案2】:

    如果你知道你想翻转的位的位置,你可以在没有外部库的情况下做到这一点。

    #! /usr/bin/env lua
    
    local hex  = 0xFF
    local maxPos  = 7
    
    local function toggle( num, pos )
        if pos < 0 or pos > maxPos then print( 'pick a valid pos, 0-' ..maxPos )
        else
            local bits = {}  --  populate emtpy table
            for i=1, maxPos do bits[i] = false end
    
            for i = maxPos, pos +1, -1 do  --  temporarily throw out the high bits
                if num >= 2 ^i then
                    num = num -2 ^i
                    bits [i +1] = true
                end
             end
    
            if num >= 2 ^pos then  num = num -2 ^pos  -- flip desired bit
            else                   num = num +2 ^pos
            end
    
            for i = 1, #bits do  --  add those high bits back in
                if bits[i] then num = num +2 ^(i -1) end
            end
    
        end ; print( 'current value:', num )
        return num
    end
    

    original value: 255
    current value: 127
    pick a valid pos, 0-7
    current value: 127
    current value: 255

    【讨论】:

    • 哦,对了,必须先扔掉高位。让我想一想
    • 条件的另一个选项是math.floor(num / (2 ^ pos)) % 2,这通过除以目标位置的值然后检查第一位来简化过程。
    • 啊,那样的话(num / (2 ^ pos)) % 2 &gt;= 1
    猜你喜欢
    • 1970-01-01
    • 2012-11-14
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2013-06-05
    相关资源
    最近更新 更多