4

I'm running this (-3 >> 1) in java and getting answer -2 but according to me, it should be -1 as I'm thinking this like -3/2. Please help me understand this.

int x = -3 >> 1;
System.out.println(x + " " + (-3 >> 1));
Abhinav Kinagi
  • 3,653
  • 2
  • 27
  • 43

2 Answers2

5

The answer results from the binary representation of -3 in Java, which is

11111111111111111111111111111101

When you shift these bits right by one you get

11111111111111111111111111111110

Which is -2.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

As negetive numbers are saved as 2's complement value for arithmetic operations

Represent -3 in 2's complement

+3 -> 0011

complement ->1100

add 1 -> 0001

-3 -> 1101

after Right shift Operation the value will be 1110 as Right shift operation for negetive number add 1 to left-most bit.

link Why does right shifting negative numbers in C bring 1 on the left-most bits?

Represent -2 in 2's complement

+2 -> 0010

complement -> 1101

add 1 ->0001

-2 = -> 1110

AkashToSky
  • 107
  • 1
  • 11