[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: Bit ops (why functions are non optimal)
- From: "Jerome Vuarand" <jerome.vuarand@...>
- Date: Fri, 22 Sep 2006 15:23:41 -0400
Lua:
> function prefix2mask(bits)
> return htonl(math.not((math.lshift(1, (32 - bits))) - 1))
> end
C:
> u_int32_t prefix2mask(int prefix) {
> return htonl(~((1 << (32 - prefix)) - 1));
> }
IMHO the Lua version is much clearer. Additionnaly,if you make it higher
level, no need to use C tricks with shifts and bitwise not. That could
be written (assuming bit.rep works like string.rep for bitfields):
> function prefix2mask(bits)
> return htonl(bit.rep(1, bits)..bit.rep(0, 32 - bits))
> end
...which is even clearer.