lua-users home
lua-l archive

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


My reply to this email:  http://lua-users.org/lists/lua-l/2006-09/msg00796.html

Sorry I had to start a new thread, but I can no longer send or recieve messages from the list on my work address for some reason.

People in the list keep brining up networking as the reason, allthough by far this is not the only reaon to use bitops, but I guess its the one most people are familiar with so I will use them here too.  Lets take an application that already exists, ipcalc for example, and take a simple example from it where bit operations are use to manipulate ip addresses. (cutting code from the source)

  \fn u_int32_t prefix2mask(int bits)
  \brief creates a netmask from a specified number of bits
u_int32_t prefix2mask(int prefix) {
    return htonl(~((1 << (32 - prefix)) - 1));
}

Thats the function in C.

Now, if we had to do that in lua with functions it would probably look something like this:

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

Ok, so its not all that ugly really, but its not as easy to read as the above C code either.  Not to mention that it requires 2 function calls, but alot of people don't care about the performence of such an operation, because its not being done a million times a second. (And I can agree with that).

Well...  Krap... I was going to write an email about why doing it in functions was bad, and doing it with ops was better, but the difference is not too bad.  Assuming we had a list of functions to make compound bit ops like test and set, or bit rmw type of ops, maybe like this?

math.bit.set(num, bit) -- num is the value to modify, and bit is a mask of bits to set
math.bit.clr(num, bit) -- same as above, but clear
math.bit.mod(num, which, value) -- num is what to modify, which is the mask to apply (which bits to modify), and value is what to set them to its the superset of the above 2 functions
math.bit.shr(num, bitstoshift) -- shift num right bitstoshift bits ( num << bitstoshift)
math.bit.shl(num, bitstoshift) -- ditto but left
math.bit.and(num1, num2) -- and the two numbers together (and is a reserved word though)
  same for or, xor
math.bit.not(num) -- well..

I think thats all.  Maybe this is an acceptable solution?  Of course I still like the ide of adding it to the language, but thats because I like my code to look small and simple, and I am attached to the ops :)

Mike