0
votes

This is an excerpt from the article on wikipedia https://en.wikipedia.org/wiki/Arithmetic_shift:

Shifting right by n bits on a two's complement signed binary number has the effect of dividing it by 2^n, but it always rounds down (towards negative infinity). This is different from the way rounding is usually done in signed integer division (which rounds towards 0).

Can someone explain what is meant by rounding towards negative infinity and rounding towards zero (and how they differ) and give examples?

What I've noticed in C: -10 >> 4 = -1 because -10 = -1*16 + 6 but -10 / 16 = 0 because -10 = 0*16 - 10 (which is the same way % works, it gives negative remainder for negative numbers in C). I don't know if this is related to the text, but wanted to give info on what I know and don't know.

1
An example: (-1)/2 = 0 (rounded towards 0), -1 (rounded towards negative infinity)njuffa
This is the same as my example, right? -1 = 0*2 -1 and also -1 = -1*2 +1.LearningMath
I am not sure where you are stuck with distinguishing between the two rounding modes. When the result is between two integers, simply choose the one indicated by the rounding mode, i.e. pick the closest integer in the direction indicated.njuffa
"Here" meaning what in particular? Another example: (-13)/4 = -3 (rounded towards zero), -4 (rounded towards negative infinity). Please clarify (in the question) what specifically you find confusing about the rounding modes. Without that it would be difficult to provide an answer because the naming seems self-explanatory.njuffa
there are multiple types of rounding: round toward zero, away from zero, to +inf, to -inf...phuclv

1 Answers

0
votes

At school I learned all numbers from 1 to 1.499[...] will round to 1 and thus from 1.5 to 1.999[...] will round to 2.

Rounding towards 0 must be understood as rounding the result to the next nearest to zero integer. So all numbers from 1 to 1.999[...] will round to 1 and all numbers from -1.999[...] to -1 will round to -1.

With rounding towards minus infinite you will round the result to the next nearest to minus infinite integer. So all numbers from 1 to 1.999[...] will round to 1 as before but all numbers from -2 to -1.000[...]1 will round to -2.

About the behavior of right shifting negative values it may depend of the language but in C, this is dangerous because implementation defined as stated in section 6.5.7 of C standard

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.