Testing if a certain bit in a number is set?

is there a recommended way to check if certain bits are set or not in a number? I didn’t find anything in the reference. On the web i see that there is a Lua bit library do we have that available?

@piinthesky - try the link below. I looked into this ages ago when I was trying to duplicate the Elite Universe. In the end I found a spreadsheet with the galaxies and planets calculated. Bit of a cheat - bit of binary code and a few specific numbers to massive spreadsheet.

Good luck with it and could you post your results if you manage to get there?

Lua bitwise ops

What you are looking for is a bit mask.
Simply put you use a bitwise AND operation and a comparison to determine if the bit is set.

In this example I’m using a bit shift operator to create the necessary mask.

function isBitSet(bit, value)
    local mask = 0x1 << bit
    return (value & mask) > 0

-- 3rd bit of 0b1011 (binary)
print(isBitSet(3, 11)) -- true

-- Roughly evaluates to:
-- mask = 0b0001 << 3 = 0b1000
-- (0b1011 & 0b1000) > 0

As for the bit library, the bitwise operators are built in to Lua 5.4 (which Codea uses). The bit library was used for Lua 5.1 I believe.

1 Like

@Steppers Perfect, thanks a lot