Shift Operators
Lesson:
Main Points:
- The << is the left-shift operator and is the same as in C and C++
- The >> is the right-shift operator and is the same as in C and C++
- The >>> is the unsigned right-shift operator and it is unique to
Java
- Left-shifting moves the bit pattern to the left and the new bits which
come in from the right are zeroes
- Right-shifting moves the bit pattern to the right and the new bit
matches whatever the left-most bit was before the shift (this preserves
sign)
- The unsigned right-shift is like the right-shift EXCEPT that the new
bits are always zeroes.
- In all cases bits that move off the end are discarded
- Shifting can only be applied to arguments of integral types
In general left-shifting doubles a value and right-shifting halves a value.
This is not 100% correct, but this is the simplest way to think of the
functionality of these operators. To understand this let's look at the
binary representation of the value 27 (as it would be represented in a 16
bit byte format):
STATE DECIMAL BINARY
27 00000000 00011011
<<3 216 00000000 11011000
>>3 3 00000000 00000011
Here you can see that if you left shift 27 three places that the resulting
value is 216 and if you right shift 27 three places the resulting value is
3.
EXAMPLE:
This applet shows the above example plus the effect of the unsigned
right-shift. Plus it shows all this stuff using a negative number.
import java.awt.*;
import java.applet.*;
public class j203 extends Applet{
int pos=27;
int neg=-27;
public void init(){
setBackground(Color.blue);
}
public void paint(Graphics g){
g.setColor(Color.yellow);
g.drawString("SHIFTING WITH A POSITIVE VALUE:",10,15);
g.drawString("Original Value: "+pos, 10, 30);
int x = pos<<3;
g.drawString("LEFT-SHIFTED 3: "+x,10,45);
x = pos>>3;
g.drawString("RIGHT-SHIFTED 3: "+x,10,60);
x = pos>>>3;
g.drawString("UNSIGNED RIGHT-SHIFTED 3: "+x,10,75);
g.drawString("SHIFTING WITH A NEGATIVE VALUE:",300,15);
g.drawString("Original Value: "+neg, 300, 30);
x = neg<<3;
g.drawString("LEFT-SHIFTED 3: "+x,300,45);
x = neg>>3;
g.drawString("RIGHT-SHIFTED 3: "+x,300,60);
x = neg>>>3;
g.drawString("UNSIGNED RIGHT-SHIFTED 3: "+x,300,75);
}
}
Assignment:
|
This assignment is a bit of a brain-buster (potentially). You will recreate
the picture shown to the left. You must demonstrate the use of the shift
operators (just the right and the left) in your code. You may use two int
variables throughout your code (one to contol a for-loop and the other to
control the height of the bars). (The picture here is a screenshot of an
applet.)
|