Java shift operator fancy program output

I came across the following program, and it behaves unexpectedly.

public class ShiftProgram
{
      public static void main(String[] args)
      {
             int i = 0;
             while(-1 << i != 0)
                   i++;
             System.out.println(i);
      }
}

If we think about this program exit when it reaches 32, while the loop condition should return false and end, and it should print 32.

If you run this program, it does not print anything, but goes into an endless loop. Any idea what is going on? Thanks in advance.

+3
source share
2 answers

Have you tried printing (-1 << i)in a loop to find out what is going on? If you do this, you will see that it goes:

-1 << 0 = -1
-1 << 1 = -2
-1 << 2 = -4
-1 << 3 = -8
-1 << 4 = -16
-1 << 5 = -32
-1 << 6 = -64
-1 << 7 = -128
-1 << 8 = -256
-1 << 9 = -512
-1 << 10 = -1024
-1 << 11 = -2048
-1 << 12 = -4096
-1 << 13 = -8192
-1 << 14 = -16384
-1 << 15 = -32768
-1 << 16 = -65536
-1 << 17 = -131072
-1 << 18 = -262144
-1 << 19 = -524288
-1 << 20 = -1048576
-1 << 21 = -2097152
-1 << 22 = -4194304
-1 << 23 = -8388608
-1 << 24 = -16777216
-1 << 25 = -33554432
-1 << 26 = -67108864
-1 << 27 = -134217728
-1 << 28 = -268435456
-1 << 29 = -536870912
-1 << 30 = -1073741824
-1 << 31 = -2147483648
-1 << 32 = -1
-1 << 33 = -2
-1 << 34 = -4
-1 << 35 = -8
-1 << 36 = -16
[.. etc ..]

According to the language specification :

n < s n s; ( ) s.

... .

, :

int, . (ยง15.22.1) 0x1f. 0 31 .

, 32, 32 & 0x1f, 0. -1, 0, -1, 0.

+6

int (32), i << 32 i << 0, i. , 0 . http://www.janeg.ca/scjp/oper/shift.html. - int n = -1; while (n != 0) {i++; n <<= 1;}, 0, .

+6

Source: https://habr.com/ru/post/1796450/


All Articles