Some alternatives for division by 4
return x/4 + (x/2 % 2);
return x/4 + (x % 4 >= 2)
Or in general, division by any power of 2
return x/y + x/(y/2) % 2; // or
return (x >> i) + ((x >> i - 1) & 1); // with y = 2^i
It works by rounding up if the fractional part ? 0.5, i.e. the first digit ? base/2. In binary it's equivalent to adding the first fractional bit to the result
This method has an advantage in architectures with a flag register, because the carry flag will contain the last bit that was shifted out. For example on x86 it can be optimized into
shr eax, i
adc eax, 0
It's also easily extended to support signed integers. Notice that the expression for negative numbers is
(x - 1)/y + ((x - 1)/(y/2) & 1)
we can make it work for both positive and negative values with
int t = x + (x >> 31);
return (t >> i) + ((t >> i - 1) & 1);