Java Reference
In-Depth Information
a ^= b;
b ^= a;
a ^= b;
the values of a and b will be interchanged, but remember this only works for integers. We can try this
out with a couple of arbitrary values for a and b , 0xD00F and 0xABAD respectively - again we will just
look at 16 bits for each variable. The first statement will change a to a new value:
a ^= b
Hexadecimal
Binary
a
0xD00F
1101
0000
0000
1111
b
0xABAD
1010
1011
1010
1101
a from a^b
0x7BA2
0111
1011
1010
0010
Now the next statement, which calculates a new value of b using the new value of a :
b ^= a
Hexadecimal
Binary
a
0x7BA2
0111
1011
1010
0010
b
0xABAD
1010
1011
1010
1101
b from b^a
0xD00F
1101
0000
0000
1111
So b now has a value that looks remarkably like the value that a started out with. Let's look at the last
step, which calculates a new value for a using the new value of b :
a ^= b
Hexadecimal
Binary
a
0x7BA2
0111
1011
1010
0010
b
0xD00F
1101
0000
0000
1111
a from a^b
0xABAD
1010
1011
1010
1101
Lo and behold, the value of a is now the original value of b . In the old days when all programmers
wore lab coats, when computers were driven by steam, and when memory was measured in bytes rather
than megabytes, this mechanism could be quite useful since you could interchange two values in
memory without having to have extra memory locations available. So if antique computers are your
things, this may turn out to be a valuable technique. In fact it's more useful than that. When we get to
do some graphics programming you will see that this is very relevant.
Don't forget - all of these bitwise operators can only be applied to integers. They don't work with any
other type of value. As with the arithmetic expressions, the bitwise operations are carried out with 32
bits for integers of type short and of type byte , so a cast to the appropriate type is necessary for the
result of the expression on the right of the assignment operator. One note of caution - special care is
needed when initializing variables of type byte and type short with hexadecimal values to avoid
being caught out. For example, you might be tempted to initialize a variable of type byte to binary
1111 1111 with the statement:
Search WWH ::




Custom Search