-3

int z = -1; int m = z>>1; System.out.println("the values is " +m);

Output is the values is -1

but my doubt is how it happening internally, Can any explain? Step by step procedure.

int z = 2; int m = z>>1;

the z value in binary

00000000 00000000 00000000 00000010 ,

After the value is shifted then the m value in binary will be as

00000000 00000000 00000000 00000001 , when I print m value it will be as 1, but my question is, what is happening if I use negative value for z variable and when I assign z value with -1 why output variable has -1 itself? ( Two complement will happen are not?)

Prakash
  • 630
  • 3
  • 10
  • 20
  • 2
    What do you mean how it happens internally? The right-shift operator is explained in the [JLS](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19). What is it that you don't understand? – RealSkeptic Jul 03 '17 at 07:10
  • Requests for "step by step" anything are generally requests for a new full tutorial written to a specification. That feels like you're not doing any work at all, and asking for a lot of volunteer effort from someone else. A good tip on Stack Overflow is to show you have made a good effort, and if you cannot show that in a question, make more of an effort first. – halfer Jul 03 '17 at 08:09

1 Answers1

0

As described in JLS Sec 15.19:

The value of n >> s is n right-shifted s bit positions with sign-extension. The resulting value is floor(n / 2^s).

So, you are calculating -1 >> 1 == floor(-1 / 2) == floor(-0.5) = -1.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • `int z = 2; int m = z>>1;` the z value in binary ` 00000000 00000000 00000000 00000010 ` , After the value is shifted then the m value in binary will be as ` 00000000 00000000 00000000 00000001 ` , when I print m value it will be as `1`, but my question is, what is happening if I use negative value for `z` variable and when I assign `z` value with `-1` why output variable has `-1` itself? ( Two complement will happen are not?) – Prakash Jul 03 '17 at 09:04
  • @Prakash you should maybe read https://en.m.wikipedia.org/wiki/Arithmetic_shift#Non-equivalence_of_arithmetic_right_shift_and_division, as it describes this specific case (albeit in 8-bit). – Andy Turner Jul 03 '17 at 09:14