【发布时间】:2021-02-24 08:30:44
【问题描述】:
我想对数字中的特定位执行设置和重置。由于我使用的是 lua 5.1,我无法使用 API 和移位运算符,所以它变得越来越复杂,所以请帮我找到这个
【问题讨论】:
标签: lua lua-table esp32 nodemcu nodemcu-build
我想对数字中的特定位执行设置和重置。由于我使用的是 lua 5.1,我无法使用 API 和移位运算符,所以它变得越来越复杂,所以请帮我找到这个
【问题讨论】:
标签: lua lua-table esp32 nodemcu nodemcu-build
bit 库随固件一起提供。
【讨论】:
dev-esp32 分支(在这种特殊情况下,模块是相同的)。
如果你知道你想翻转的位的位置,你可以在没有外部库的情况下做到这一点。
#! /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: 255current value: 127pick a valid pos, 0-7current value: 127current value: 255
【讨论】:
math.floor(num / (2 ^ pos)) % 2,这通过除以目标位置的值然后检查第一位来简化过程。
math:nodemcu.readthedocs.io/en/latest/lua-developer-faq/…
(num / (2 ^ pos)) % 2 >= 1