<h2>Java's Bitwise Operators</h2> <h3>Logical Operators</h3> <table border align=center> <tr><td width=20>&amp;<td>bitwise AND <tr><td>|<td>bitwise OR <tr><td>^<td>bitwise exclusive OR ie XOR <tr><td>~<td>bitwise inverter, eg ~1101 becomes 0010 </table> <h3>Shift Operators</h3> <table border align=center> <tr><td width=50>&lt;&lt;<td>Shift left (shifting zero bits in from the right) <tr><td>&gt;&gt;<td>Shift right (shifting with sign bits in from the left) <tr><td>&gt;&gt;&gt;<td>Shift right (shifting zero bits in from the left) </table> <p><table> <tr><td>1101<td align=center>&lt;&lt;<td>2 becomes 0100 <tr><td>1101<td align=center>&gt;&gt;<td>2 becomes 1111 <tr><td>1101<td align=center>&gt;&gt;&gt;<td>2 becomes 0011 </table> <p align=justify> The number of bit-places shifted (the right operand) is the number you provide masked by (the size of the type of the left-hand operand) - 1. So if the left-hand operand is a 32-bit <tt>int</tt>, the mask is 31 <p><table> <tr><td>so a shift of<td width=40 align=right>+35&nbsp;&nbsp;<td>00000000000000000000000000100011 <tr><td>or a shift of<td width=50 align=right>&minus;29&nbsp;&nbsp;<td>11111111111111111111111111100011 <tr><td>masked by<td width=50 align=right>31&nbsp;&nbsp;<td>00000000000000000000000000011111 <tr><td>both yield<td width=50 align=right>+3&nbsp;&nbsp;<td>00000000000000000000000000000011 </table> <p align=justify> Bitwise operators <tt>&amp;</tt> and <tt>|</tt> can be used on boolean variables in place of <tt>&amp;&amp;</tt> and <tt>||</tt>. However unlike <tt>&amp;&amp;</tt> and <tt>||</tt>, <tt>&amp;</tt> and <tt>|</tt> always evaluate both operands before returning their result - so beware. <p align=justify> A converse logical XOR test can be constructed using the bitwise XOR operator <tt>^</tt> which returns a <tt>true</tt> if the expressions evaluate to opposite boolean states and <tt>false</tt> if to the same boolean state as in: <pre>if((x &lt; 0)^(y &lt; 0)) DiffSign(); else SameSign();</pre> <hr> &copy; 1998 Robert John Morton