Why does the right shift operator produce zero instead of one?

I teach myself java and I work on thinking exercises in Java.

On page 116, exercise 11, you must shift the integer over all of your binary positions and display each position using Integer.toBinaryString.

public static void main(String[] args) {
int i = 8;
System.out.println(Integer.toBinaryString(i));
int maxIterations = Integer.toBinaryString(i).length();
int j;
for (j = 1; j < maxIterations; j++) {
    i >>= 1;
System.out.println(Integer.toBinaryString(i));
}

In the solution guide, the output is as follows:

1000
1100
1110
1111

When I run this code, I get the following:

1000
100
10
1

What's going on here. Are the numbers cut off?

I am using jdk1.6.0_20 64bit. The book uses jdk1.5 32bit.

+3
source share
6 answers

There seems to be a mistake in the book.

, . , (, ).

00001000
00000100
00000010
00000001
00000000

, :

  • 0,
  • 1, .

, , , , -8 8.

11111111111111111111111111111000
11111111111111111111111111111100
11111111111111111111111111111110
11111111111111111111111111111111

>>> >>, , , .

+9

, .

, , , , :

00001000
00000100
00000010
00000001
00000000
00000000
+3

Java:

" → > " , " → " .

8 , . i , ( ).

+3

, ..

01000
00100
00010
00001

"" , . , .

+2

int,

int i = 1 << 31;

, . , , .

10000000000000000000000000000000
11000000000000000000000000000000
11100000000000000000000000000000
11110000000000000000000000000000
11111000000000000000000000000000
11111100000000000000000000000000
11111110000000000000000000000000
....
11111111111111111111111111111000
11111111111111111111111111111100
11111111111111111111111111111110
11111111111111111111111111111111
+1

, , variable >>= 1 . 1 , . , . >>> .

+1
source

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


All Articles