Java – why does the shift right operator produce zero instead of one?

I'm learning Java by myself. I practice in thinking in Java

On page 116, exercise 11, you should move an integer right to all its binary positions and use integer Tobinarystring displays each location

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 this:

1000
100
10
1

What happened here Is the number truncated?

I use jdk1 6.0_ 20 64bit. This book uses jdk1 5 32bit.

Solution

It seems that there are mistakes in the book

The shift right operation shifts all bits to the right, removing the least significant bit This makes more sense if you align the results correctly (for example, by filling with zeros)

00001000
00000100
00000010
00000001
00000000

The highest bit moved in is:

> 0 if your number is positive, > 1 if your number is negative

If you want the final result to be 1, try using a negative number – such as - 8 instead of 8

11111111111111111111111111111000
11111111111111111111111111111100
11111111111111111111111111111110
11111111111111111111111111111111

If you use > > > instead of > >, then, whether the number is positive or negative, zero will always move in

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>