I am doing this..
value >> 3;
It is always going toward negative side.How do I round toward zero with right shift division?
Gez, the answers were pretty bad ; you want to solve that without branching, but without breaking your positive numbers either.
Here it is :
(int)(value+(((unsigned)value)>>31)) >> 3
The cast to (unsigned) is required to perform a logical shift and obtain just the sign bit, then we need to cast back to (int) to perform an arithmetic right shift.
The code above made the assumption that your int data type is 32 bits, you should of course use data types such as int32_t in such cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With