i am teaching myself java and i work through the exercises in Thinking in Java.
On page 116, exercise 11, you should right-shift an integer through all its binary positions and display each position with 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 looks like this:
1000
1100
1110
1111
When i run this code i get this:
1000
100
10
1
What is going on here. Are the digits cut off?
I am using jdk1.6.0_20 64bit. The book uses jdk1.5 32bit.
It looks like there is an error in the book.
The right shift operation shifts all bits to the right, removing the least significant bit. This makes a lots more sense if you right align the results (by padding with zeros, for example).
The topmost bit shifted in is:
If you want the final result to be ones then try using a negative number like -8 instead of 8.
If you use
>>>instead of>>then a zero will always be shifted in, regardless of whether the number is positive or negative.