问题描述
我想对数字中的特定位进行设置和重置。当我使用lua 5.1时,我无法使用API和移位运算符,因此它变得越来越复杂,请帮助我找到这个
解决方法
bit
库随固件一起提供。
阅读文档:https://nodemcu.readthedocs.io/en/release/modules/bit/
,如果知道要翻转的位的位置,则可以在没有外部库的情况下进行操作。
filename_202011120001.zip
filename_202011120002.tar.gz
filename_202011120003.rar
filename_202011120004.tar.bz2
#! /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