Java Reference
In-Depth Information
Shift operations are often used
in combination with the other
bitwise operators we have
discussed to extract parts of an
integer value. In many
operating systems a single 32-
bit value is sometimes used to
store multiple values - two 16-
bit values, for instance, that
might be screen coordinates.
This is illustrated opposite.
coordinate x
coordinate y
value
0 0 1 0 0 1 1 0 1 1 0 0 1 1 0 1
0 1 0 0 0 1 1 0 1 1 1 0 1 1 0 0
x = value>>>16;
// Extract x from value(assumed positive)
x
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 1 1 0 1 1 0 0 1 1 0 1
y = value & 0xFF;
// Extract y from value(assumed positive)
y
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 1 1 0 1 1 1 0 1 1 0 0
x = value>>16;
// Extract x from value(positive or negative)
x
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 1 1 0 1 1 0 0 1 1 0 1
y = (value << 16) >> 16;
// Extract y from value(positive or negative)
y
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 1 1 0 1 1 1 0 1 1 0 0
This shows how the shift operations can be used to extract either the left or the right 16 bits from the variable
value. You can see here why you have an extra shift right operation that propagates the leftmost bit. It is
related to the notion of a shift as multiplying or dividing by a power of 2, and the implications of that in the
context of negative integers represented in 2's complement form (see Appendix B).
Boolean Variables
Variables that can only have one of two values, true or false , are of type boolean , and the values
true and false are boolean literals. You can define a boolean variable, called state , with the
statement:
boolean state = true;
This statement also initializes the variable state with the value true . You can also set a boolean
variable in an assignment statement. For example, the statement:
state = false;
sets the value of the variable state to false .
At this point we can't do much with a boolean variable, other than to set its value to true or false , but,
as you will see in the next chapter, Boolean variables become much more useful in the context of decision
making in a program, particularly when we can use expressions that produce a boolean result.
There are several operators that combine Boolean values including operators for Boolean AND,
Boolean OR, and Boolean negation (these are &&, ||, and !, respectively), as well as comparison
operators that produce a Boolean result. Rather than go into these here in the abstract, we will defer
discussion until the next chapter where we will also look at how we can apply them in practice to alter
the sequence of execution in a program.
Search WWH ::




Custom Search