lua-users home
lua-l archive

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


I've been following the discussion on the bit32 library and share the desire
for an operator rather than a functional syntax. However I realised that 99%
of my use of this library is for cracking and assembling bitfields for
communications protocols and register mapping in embedded systems. It is
straightforward to add a syntax for this in a C library by providing a
metatable for the number type with 'index' and 'newindex' metamethods. Then:

b = n[3]        -- Extract bit 3 as a boolean.
n[23] = true    -- Set bit 23.
n[6] = not n[6] -- Toggle bit 6.

If you really need to bitwise and two numbers:

for i=0, 31 do nr[i] = n1[i] and n2[i] end

Nowhere near as efficient as:

nr = bit32.band(n1,n2)

But more expressive and intuitive especially when you need to manipulate a
few bits in relatively complex ways.

This concept can be extended to extract and replace numeric fields within a
larger field (like the bit32 functions with these names). This requires that
the index encode two five bit integers which could be done using bitfields
within a single number or by using a string index which gets parsed in the
metamethod:

bitrange = function(s,e) return ((e * 0xFF) + 1) + s end  -- Range testing
omitted for clarity

nr = n[bitrange(10,15)]  -- Mask out bits 10 through 15 and shift right 10.
nr = n[bitrange(15,10)]  -- Mask out bits 10 through 15, shift and reverse
the bit order.
nr = n[bitrange(12,12)]  -- nr = 1 if bit 12 is set, else 0.
b = n[bitrange(12)]      -- b = true only if bit 12 is set (as before).
n[bitrange(4,6)] = 2     -- replace bits 4 through 6 with 010.