title: Most elegant way to convert a byte to an int in Java
body: <p>Example code:</p>
  
  <pre><code>int a = 255;
  byte b = (byte) a;
  int c = b &amp; 0xff; // Here be dragons
  System.out.println(a);
  System.out.println(b);
  System.out.println(c);
  </code></pre>
  
  <p>So we start with an integer value of 255, convert it to a byte (becoming -1) and then converting it back to an int by using a magic formula. The expected output is:</p>
  
  <pre><code>255
  -1
  255
  </code></pre>
  
  <p>I'm wondering if this <code>a &amp; 0xff</code> is the most elegant way to to this conversion. <a href="http://checkstyle.sourceforge.net/" rel="noreferrer">checkstyle</a> for example complains about using a magic number at this place and it's not a good idea to ignore this value for this check because in other places 255 may really be a magic number which should be avoided. And it's quite annoying to define a constant for stuff like this on my own. So I wonder if there is a standard method in JRE which does this conversion instead? Or maybe an already defined constant with the highest unsigned byte value (similar to Byte.MAX_VALUE which is the highest signed value)</p>
  
  <p>So to keep the question short: How can I convert a byte to an int without using a magic number?</p>
  
  <p>Ok, so far the following possibilities were mentioned:</p>
  
  <ul>
  <li>Keep using <code>&amp; 0xff</code> and ignore the magic number 255 in checkstyle. Disadvantage: Other places which may use this number in some other scope (not bit operations) are not checked then, too. Advantage: Short and easy to read.</li>
  <li>Define my own constant for it and then use code like <code>&amp; SomeConsts.MAX_UNSIGNED_BYTE_VALUE</code>. Disadvantage: If I need it in different classes then I have to define my own constant class just for this darn constant. Advantage: No magic numbers here.</li>
  <li>Do some clever math like <code>b &amp; ((1 &lt;&lt; Byte.SIZE) - 1)</code>. The compiler output is most likely the same because it gets optimized to a constant value. Disadvantage: Pretty much code, difficult to read. Advantage: As long as <code>1</code> is not defined as magic number (checkstyle ignores it by default) we have no magic number here and we don't need to define custom constants. And when bytes are redefined to be 16 bit some day (Just kidding) then it still works because then Byte.SIZE will be 16 and not 8.</li>
  </ul>
  
  <p>Are there more ideas? Maybe some other clever bit-wise operation which is shorter then the one above and only uses numbers like 0 and 1?</p>