I am doing this..
value >> 3;
It is always going toward negative side.How do I round toward zero with right shift division?
I am doing this..
value >> 3;
It is always going toward negative side.How do I round toward zero with right shift division?
Do something conditionally depending on whether your value is positive or negative.
if( value < 0 ) {
-((-value) >> 3);
}
else {
value >> 3;
}
Try the following expression instead:
(value < 0) ? -((-value) >> 3) : value >> 3;
That will force a negative number to be positive first so that it round towards zero, then changes the result back to negative.
You are encountering 'signed' shifting, when what you seem to want is unsigned shifting. Try casting it to unsigned first, like this
x = ((unsigned) x) >> 3;
.. or you could just use 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.