Re: int32 multiplication, with truncation on overflow

  • From: Mike Pall <mike-1405@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Thu, 1 May 2014 11:51:35 +0200

Duncan Cross wrote:
>  local bit = require 'bit'
> 
>  result = tonumber(bit.arshift(bit.lshift((0LL + a) * (0LL + b), 32), 32))

You can drop one widening. And bit.tobit() is the function you
want to use for truncating 64 bit to 32 bit.

The JIT-compiler knows how to turn that all of that into a
truncating 32 bit multiply:

$ luajit -jdump -e "local x = 1; for i=1,201,2 do x = bit.tobit(x*(i+0LL)) end; 
print(x)"
...
0bcaffe3  imul ebp, r15d  // 32 bit * 32 bit => 32 bit multiply 
...
2114520369

--Mike

Other related posts: