Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 4 ■ OPERATORS

System.out.println("b as binary: " + Integer.toBinaryString(b));
String leftShiftString = Integer.toBinaryString(b<<3);
System.out.println("binary after signed left shifting 3 places: " +
leftShiftString);
System.out.println("value of b after signed shifting left 3 places: " +
Integer.parseInt(leftShiftString, 2));
String rightShiftString = Integer.toBinaryString(b>>3);
System.out.println("binary after signed shifting right 3 places: " +
rightShiftString);
System.out.println("value of b after signed shifting right 3 places: " +
Integer.parseInt(rightShiftString, 2));
String unsignedRightShiftString = Integer.toBinaryString(b>>>3);
System.out.println("binary after unsigned shifting right 3 places: " +
unsignedRightShiftString);
System.out.println("value of b after unsigned shifting right 3 places: " +
Integer.parseInt(unsignedRightShiftString, 2));
b = -128;
System.out.println("Resetting b to " + b);
System.out.println("b as binary: " + Integer.toBinaryString(b));
unsignedRightShiftString = Integer.toBinaryString(b>>>3);
System.out.println("binary after unsigned shifting right 3 places: " +
unsignedRightShiftString);
System.out.println("value of b after unsigned shifting right 3 places: " +
Integer.parseInt(unsignedRightShiftString, 2));
}
}


Running ShiftDemo produces the following output (see Listing 4-11):

Listing 4-11. ShiftDemo output


b: 127
b as binary: 1111111
binary after signed left shifting 3 places: 1111111000
value of b after signed shifting left 3 places: 1016
binary after signed shifting right 3 places: 1111
value of b after signed shifting right 3 places: 15
binary after unsigned shifting right 3 places: 1111
value of b after unsigned shifting right 3 places: 15
Resetting b to -128
b as binary: 11111111111111111111111110000000
binary after unsigned shifting right 3 places: 11111111111111111111111110000
value of b after unsigned shifting right 3 places: 536870896


ShiftDemo and its output reveal a number of things worth knowing about the shift operators:


  • The left-hand operator represents the value to be shifted, and the right-hand
    operator indicates the number of bits by which to shift (known as the shift
    distance).

Free download pdf