NTP shift_right cleanup (v. A3)
- For fixed shifts, you can just write it as a divide; GCC will DTRT. For interest's sake, GCC 4.0 generates, for x /= 64:
testl %eax, %eax jns .L2 addl $63, %eax .L2: sarl $6, %eax
- If you want to be more verbose with the explanation, try something like:
(Public domain, copyright abandoned, use freely, yadda yadda.)
/*
* NTP uses power-of-two divides a lot for speed, but it wants to use
* negative numbers.
* 1) ANSI C does not guarantee signed right shifts (but GCC does)
* 2) Such a shift is like a divide that rounds to -infinity.
* NTP wants rounding to zero, i.e. -3/2 = -2, while -3>>1 = -2.
*/
Interestingly, _Hacker's Delight_ chapter 10 skips over this particular case, signed division by a variable power of two.