lua-users home
lua-l archive

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

Friday, September 22, 2006, 4:58:05 PM, Mike Pall wrote:

> I've previously posted a patch with a minimal set of 4 functions:

> [...]

> Bit operations work fine with negative numbers and may produce
> negative numbers, too.

The C Standards (IIRC) do not specify whether right shift propagates
the sign bit (and don't specify twos complement, either, though that
doesn't concern me much in practice).

Mike, your implementation of bit_field along with the statement above
seems to imply an assumption that >> propagates the sign bit.

Reuben's lbitlib provides both signed and unsigned right shifts, but
seems to make the assumption that >> propagates the sign bit for
signed long long and not for unsigned long long. Fortunately the
compiler I am using (gcc on x86) does just that, it seems.

Anyway, it's often necessary to sign extend an arbitrary sized field,
e.g., a small field representing a signed quantity from the middle of
a larger bit string. An optional argument to your math.bitfield
function would solve both problems...

  y... = math.bitfield(x, start [, len [, signextend]]...)
    'start' is the bit position relative to the lsb (bit 0)
    It's a right/left shift for a positive/negative 'start'.
    It's a pure shift if 'len' is omitted.
    Otherwise the result is masked to 'len' valid bits,
    and if signextend is true, the most significant bit of
    the bitfield is sign extended to fill the integer result,
    otherwise the bitfield is zero extended to the left.



Doug Currie
Londonderry, NH