Quick quiz: how do you rewrite the statement below, which alternates between two constants, without a conditional?

if (x == a) x= b;
  else x= a;

Answer:

x= a ^ b ^ x;
//where x is equal to either a or b

The ^ character is the logical XOR operator. How does the code work? With XOR, doing the operation twice always gives you back the original result.

Case 1: x equals a  Case 2: x equals b  
x= a ^ b ^ x x= a ^ b ^ x Use formula
x= a ^ b ^ a x= a ^ b ^ b Substitute
x= b ^ a ^ a x= a ^ b ^ b Reorder variables
x= b x= a The last two variables cancel out

Java programs are pretty far removed from the bit-crunching machines and operating systems on which they run. While modern CPUs often have special instructions to manipulate bitsets, you certainly can't execute these instructions in Java. The JVM supports only signed and unsigned shift, and bitwise XOR, OR, AND, and NOT. Ironically, Java programmers find themselves in the same boat with many assembly programmers who happened to be targeting CPUs, in lacking extra bitwise instructions. The assembly programmers had to emulate these instructions, as quickly as possible, in software. Many of the new Tiger methods do just this in pure Java.
更多请进入http://www.onjava.com/pub/a/onjava/2005/02/02/bitsets.html下查看

posted on 2005-10-13 01:13  java  阅读(214)  评论(0编辑  收藏  举报