Re: small gotcha with cdata and number

  • From: Mike Pall <mike-1205@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 30 May 2012 19:57:04 +0200

William Adams wrote:
> As part of a SHA1 calculation, there is this function
> 
> which will add two 32-bit numbers, and ensure the 
> 
> result is still 32 bits.
> 
> -- adding 2 32bit numbers, cutting off the remainder on 33rd bit
> local function w32_add (a,b)
>  return (a+b) % 4294967296
> end

Ick, please don't do that -- it's very slow.

Use bit.tobit(a+b) explicitly, if you must. But you can avoid that
in most cases, since you're passing these things to other bit.*
functions, which implicitly perform the bit.tobit() conversion.

In fact, the JIT compiler optimizes a+b passed to a bit operation
into a simple 32 bit integer ADD in the machine code.

The Lua BitOp distribution has an example MD5 implementation that
generates pretty good code with LuaJIT 2.0: http://bitop.luajit.org

--Mike

Other related posts: