lua-users home
lua-l archive

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


Mike Panetta <panetta.mike <at> gmail.com> writes:

> function prefix2mask(bits)
>     return htonl(math.not((math.lshift(1, (32 - bits))) - 1))
> end

I'd say instead:

  function prefix2mask(bits)
      return htonl( 2^32 - 2^(32-bits) )
  end

Too slow?  Well, there's only 33 possible inputs, so cache 'em:

  prefix2mask = {}
  for bits = 0,32 do
    prefix2mask[bits] = htonl( 2^32 - 2^(32-bits) )
  end

My point is that, often, people claim to need bitops because
they are used to thinking in C, or are translating C code naively.