lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 23 November 2010 20:14, Patrick Rapin <toupie300@gmail.com> wrote:
> Thank you for the answer.
> Now another point about the bit32 library. Several years ago I write
> my own "bit" library, before understanding that several versions had
> already been implemented :~)
> While comparing the features of my bit library and the new standard
> bit32 one, I noticed that IMHO two functions are missing in the
> standard version.
> I call them get and set. We used them quite a lot to deal with bit
> fields from hardware registers. This is how they could be defined:
>
> bit32.get(x, disp [, nbbits]) : returns the bit slice taken from
> number 'x', starting at bit # 'disp', and of size 'nbbits' bits (1 by
> default).
> Examples:
>  assert(bit32.get(0x12345678, 4, 4) == 0x7)
>  assert(bit32.get(0x12345678, 16, 8) == 0x34)
>  assert(bit32.get(0x12345678, 3) == 1)
>
> bit32.set(val, x, disp [, nbbits]) : inserts the value 'val' as a bit
> slice into number 'x', starting at bit position 'disp', and of size
> 'nbbits' bits (1 by default). The number 'val' must be an integer
> between 0 and 2^nbbits-1.
> Examples:
>  assert(bit32.set(0xA, 0x12345678, 0, 4) == 0x1234567A)
>  assert(bit32.set(0xFE, 0x12345678, 4, 8) == 0x12345FE8)
>  assert(bit32.set(1, 0x12345678, 30) == 0x52345678)
>
> Sure, these functions can be written in terms of bit32.band,
> bit32.lshift, bit32.rshift and bit32.bor. But would they not be better
> implemented in C inside the library?
>
>

Perhaps a more natively Lua approach to bit testing could use lookup
tables. This allows multiple tests to happen simultaneously, and Lua’s
flexibility allows the lookup table to contain functions, parameters,
or any type.

See this very idiosyncratic example below:

local function Bit2On(bit0status)
    local s = "Bit 2 is on, "
    if bit0status then
        s = s .. "and so is bit 0"
    else
        s = s .. "but not bit 0"
    end
    print(s)
end

local function Bit0On()
    print("Bit 0 is on, but not bit 2")
end


local lookupTable = {
    [0x05] = { f = Bit2On, true },
    [0x04] = { f = Bit2On, false },
    [0x01] = { f = Bit0On },
}

function CheckBits2and0(n)
    local t = lookupTable[bit32.band(n, 0x05)]
    if t then
        t.f(table.unpack(t))
    else
        print("Neither bit is on")
    end
end

CheckBits2and0(0xff)
--> Bit 2 is on, and so is bit 0
CheckBits2and0(0xfffffffb)
-->Bit 0 is on, but not bit 2
CheckBits2and0(0x04)
--> Bit 2 is on, but not bit 0
CheckBits2and0(0xa)
--> Neither bit is on


Vaughan