I wrote the following function:
int divideBy2Power(int x, int y) { return (x >> y) + (x < 0 && x << (32 - y)); }
which is supposed to compute {x / (2^y)} (rounding towards zero) in an extremely efficient manner (i.e. without branching!)
In testing it works for most inputs, but for divideBy2Power(-2, 0)
it produces -1
. Likewise, x=-1, y=0
produces 0
(not -1
). It works for bunches of other negative numbers.
I'm on a 32-bit machine and I checked that x << 32
produces zero.
Any ideas?