Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right shift (Division) -> ROUND TOWARD ZERO

I am doing this..

value >> 3;

It is always going toward negative side.How do I round toward zero with right shift division?

like image 744
RealHIFIDude Avatar asked Jul 09 '26 12:07

RealHIFIDude


1 Answers

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.

like image 184
Alexis Naveros Avatar answered Jul 12 '26 01:07

Alexis Naveros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!