Hacker News new | ask | show | jobs
by jrmuizel 5118 days ago
(x+1)>>1 isn't equivalent to x/2. It gives the wrong result for positive numbers like (x=1).

Compilers actually generate (x+(x>>31))>>1 for signed division by 2. Which on x86 is three more instructions and requires an additional register.

Using x>>1 makes sense if you want floored division instead of truncating towards zero. Floored division is better if you want to reduce precision of the input or something like that and don't want to bias towards zero.