1

I want to perform set and reset of particular bit in a number. As I'm using lua 5.1 I can't able to use APIs and shifting operators so it is becoming more and more complex so please help me finding this

Abhi
  • 73
  • 8

2 Answers2

2

bit library is shipped with the firmware.

Read the documentation: https://nodemcu.readthedocs.io/en/release/modules/bit/

Spar
  • 1,582
  • 9
  • 16
  • The OP uses ESP32 apparently. Hence, the link should point to the `dev-esp32` branch (in this particular case the module is the same). – Marcel Stör Nov 14 '20 at 17:01
1

You can do it without external libraries, if you know the position of the bit you wish to flip.

#! /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

Doyousketch2
  • 2,060
  • 1
  • 11
  • 11
  • oh yer right, have to throw out high bits first. lemme think for a sec – Doyousketch2 Nov 12 '20 at 15:26
  • Another option for the condition would be `math.floor(num / (2 ^ pos)) % 2` this simplifies the process by dividing by the value of the target position then checking the first bit. – Nifim Nov 12 '20 at 16:02
  • @Nifim there's no `math` in NodeMCU: https://nodemcu.readthedocs.io/en/latest/lua-developer-faq/#how-is-nodemcu-lua-different-to-standard-lua – Marcel Stör Nov 14 '20 at 17:00
  • 1
    Ah, in that case `(num / (2 ^ pos)) % 2 >= 1` – Nifim Nov 15 '20 at 22:39