3

In case of unsigned integer u, we can easily get quotient with u>>k(k means divide by 2^k)

But in case of negative numbers, it should be computed as (u+(1<<k)-1)>>k

I can see that u>>k does not work for negative numbers.

But I am curious why we exactly have to add (1<<k)-1 to u

Any explanations might really be helpful.

jwkoo
  • 2,393
  • 5
  • 22
  • 35
  • In most programming languages, integer division is defined to round towards zero, while an *arithmetic* right shift rounds towards negative infinity. – njuffa Sep 28 '19 at 03:05
  • cf. https://stackoverflow.com/questions/53746160/how-to-implement-arithmetic-right-shift-in-c – DaBler Jan 16 '20 at 15:56

0 Answers0