0

Hey i was trying to run the following block of code which actually Right shifts a Negative Integer number using negative shift value. Something like (negative integer)>>(negative shift value).

But interestingly what is found is that what is that whatever the value of shift & The value of integer every time it produces a result of -1. Plz Explain why the answer is always -1.

Example:

      -8>>-9
      Result: -1
      -10>>-8
      Result: -1
      -8>>-2
      Result: -1

This question is actually about how negative shift values work on negative integer integer values for right shifting using >> and not about simple Binary right shifts.

Prometheus
  • 35
  • 10
  • 1
    Read this http://geekexplains.blogspot.co.il/2009/05/binary-rep-of-negative-numbers-in-java.html – GuyKhmel Dec 27 '17 at 15:47
  • @GuyKhmel Thanks for the URL. But what i really want to know is what does right shifting with a negative shift value actually does? – Prometheus Dec 27 '17 at 15:51
  • @Prometheus Another article I found is this: http://www.informit.com/articles/article.aspx?p=30868&seqNum=6 Check out the last example – GuyKhmel Dec 27 '17 at 15:56
  • @GuyKhmel Please be more Specific. – Prometheus Dec 27 '17 at 15:59
  • The result is not *always* -1, that just tends to happen when the negative numbers are both close to zero. – harold Dec 27 '17 at 16:01
  • @Prometheus, in their example they show the following: `int j = -20;` `int result2 = j >> 2; // result = -5` So the shift right when the case is negative numbers on both is the same as positive – GuyKhmel Dec 27 '17 at 16:02
  • @NikhilYekhe That post doesn't appear to cover shifting negative values. – Bernhard Barker Dec 27 '17 at 16:35
  • You may also want to take a look at [Java: right shift on negative number](https://stackoverflow.com/q/15457893) – Bernhard Barker Dec 27 '17 at 16:46

1 Answers1

-1

My explanation would be this:

According to This article

Shift right is the same as dividing it by a power of two. Same goes when you use negative numbers on both sides (-8>>-9) just with negative values. For example -8>>-1 => -4

And when you come down to -1 then you get -1 / 2 => -1 like the behaviour in for Integers

GuyKhmel
  • 505
  • 5
  • 15
  • Shifting with -9 actually shifts with `-9 & 0x1f` == 17 for int or `-9 & 0x3f` == 37 for long, the -1 is simply because in Java shifting left with `>>` uses sign-extension, and both 17 and 37 will shift out any zero bits in the case of -8. – Mark Rotteveel Dec 27 '17 at 17:11
  • Oops, that should have read "shifting right"... – Mark Rotteveel Dec 27 '17 at 18:37