Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In Java the <code>byte</code> primitive is signed and has a range from -128 to 127, which means your <code>ba[0]</code> comes out as <code>-1</code>, whereas <code>0xFF</code> is interpreted as an int as <code>255</code>. If you do a bitwise AND with <code>0xFF</code> using the <code>&amp;</code> operator this converts the signed byte to the correct value and your code will work, as follows:</p> <pre><code> File imgFile = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg"); byte[] ba = Files.toByteArray(imgFile); //Its a google guava library int i = 0; if((ba [i] &amp; 0xFF) == 0xFF &amp;&amp; (ba[i+1] &amp; 0xFF) == 0xD8 &amp;&amp; (ba[i+2] &amp; 0xFF) == 0xFF &amp;&amp; (ba[i+3] &amp; 0xFF) == 0xE0) { System.out.println("isJPEG"); } </code></pre> <p>I'm not sure about the exact logic you are using however, as wikipedia states that the magic numbers for JPEGs are as follows:</p> <blockquote> <p>JPEG image files begin with FF D8 and end with FF D9</p> </blockquote> <p><code>FF E0</code> is JFIF specific, so you may want to double check why you are checking for this</p> <p>The following would be the code to use to make the checks as per Wikipedia:</p> <pre><code> File imgFile = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg"); byte[] ba = Files.toByteArray(imgFile); //Its a google guava library int i = 0; if((ba [i] &amp; 0xFF) == 0xFF &amp;&amp; (ba[i+1] &amp; 0xFF) == 0xD8 &amp;&amp; (ba[ba.length - 2] &amp; 0xFF) == 0xFF &amp;&amp; (ba[ba.length - 1] &amp; 0xFF) == 0xD9) { System.out.println("isJPEG"); } </code></pre>
 

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