EFFECTIVE BIT SHIFTING WITH JAVA Many programmers come to Java from C and related languages where techniques like bit shifting are commonplace. Without a good understanding of the idiosyncrasies of Java, however, the use of bit shift operators can be frustrating and lead to unexpected results. Many operations on primitive data types smaller than an int (32 bits) perform implicit promotions to an int type that cause bit shifts to fail unexpectedly. For example, consider this snippet: byte aByte = -15; aByte = (byte) (aByte >> 4); In C, this construct would cause aByte to have a value of 0x0f. In Java, the implicit promotion to an int (or larger type in some implementations) that occurs before the shift operation causes the result to become 0xff when cast to a byte. To fix this problem when working with bytes or shorts, you'll need to mask off the unwanted bytes created by the int promotion, as here: byte aByte = -15; aByte = (byte) ((aByte & 0xff) >> 4); This construct will create the expected result (0xf). If you need to use bitwise shift operators, be sure to test your code thoroughly and be aware of the differences between Java and other languages that may look similar but behave quite differently. By watching for implicit int promotions and masking off the resulting unwanted bits, you can bit shift reliably and predictably. ------------------------------------------