Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The issue here is that bitwise operators work on ints or longs, not bytes. <code>b &amp; 0xF</code> is essentially treated as <code>((int)b) &amp; ((int)0xF)</code>. You can trace it all from the JLS definitions of each operation.</p> <ul> <li>First <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.1" rel="nofollow">JLS 15.22.1</a> (which defines <code>&amp;</code> and <code>|</code>) explains that when both operands are convertible to integer primitive types, "binary numeric promotion is first performed on the operands (§5.6.2)."</li> <li><a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2" rel="nofollow">JLS 5.6.2</a>, in turn, says that unless either operand is a <code>float</code>, <code>double</code> or <code>long</code>, both values are widened to <code>int</code>.</li> <li>Finally, widening is defined in <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.2" rel="nofollow">JLS 5.1.2</a> and states that "widening conversion of a signed integer value to an integral type T simply sign-extends the two's-complement representation of the integer value to fill the wider format." Bytes are signed (<a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2" rel="nofollow">JLS 4.2</a>).</li> </ul> <p>So, your <code>b</code> byte is widened to an <code>int</code> using sign extension before being AND'd or OR'ed with the right operand.</p> <p>Note that this would imply that the result of <code>b &amp; 0F</code> should be an <code>int</code>, not a <code>byte</code>. This is in fact the case (meaning that your explicitly casting it to <code>int</code> is superfluous). You can test this by auto-boxing it to an <code>Object</code> and then checking that object's type:</p> <pre><code>byte b = -1; Object o = (b &amp; 0xF); System.out.println(o.getClass()); // prints "class java.lang.Integer", not "class java.lang.Byte" </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload