Hacker News new | past | comments | ask | show | jobs | submit login

They don't have the same results if x is signed (-1 >> 1 gives you -1; -1 / 2 typically gives you 0). A compiler worth its salt will optimize x / 2 appropriately. For unsigned, it will emit the shift; for signed, it will generate (x + 1) >> 1.



(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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: