Difference in outputs between C# and java
<p>I am trying to write a Java equivalent for a function in C#. The code follows. </p>

<p>In C#:</p>

<pre><code>byte[] a = new byte[sizeof(Int32)];
readBytes(fStream, a, 0, sizeof(Int32)); //fstream is System.IO.Filestream
int answer = BitConverter.ToInt32(a, 0);
</code></pre>

<p>In Java:</p>

<pre><code>InputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
byte[] a = new byte[4];
readBytes(in, a, 0, 4);
int answer = byteArrayToInt(a);
</code></pre>

<p>Both Java and C#:</p>

<pre><code>int readBytes(Stream stream, byte[] storageBuffer, int offset, int requiredCount)
        {
            int totalBytesRead = 0;
            while (totalBytesRead &lt; requiredCount)
            {
                int bytesRead = stream.Read(
                                storageBuffer,
                                offset + totalBytesRead,
                                requiredCount - totalBytesRead);
                if (bytesRead == 0)
                {
                    break; // while
                }

                totalBytesRead += bytesRead;
            }

            return totalBytesRead;
        }
</code></pre>

<p>Output: </p>

<pre><code>In C#: answer = 192  (Correct)  
In JAVA: answer = -1073741824 
</code></pre>

<p>There is a difference in the two.I am reading from a file input stream which is encoded and parsing the first four bytes. The C# code seems to produce 192 which is the correct answer while Java produces -1073741824 which is the wrong answer.  Why and how ?    </p>

<p><strong>EDIT</strong></p>

<p>Here is my byteArrayToInt </p>

<pre><code>public static int byteArrayToInt(byte[] b, int offset) {
        int value = 0;
        for (int i = 0; i &lt; 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (b[i + offset] &amp; 0x000000FF) &lt;&lt; shift;
        }
        return value;
    }
</code></pre>

<p><strong>SOLUTION</strong> 
The right solution for byteArrayToInt</p>

<pre><code>public static int byteArrayToInt(byte[] b) 
    {
        long value = 0;
        for (int i = 0; i &lt; b.length; i++)
        {
           value += (b[i] &amp; 0xff) &lt;&lt; (8 * i);
        }
        return (int) value;
    }
</code></pre>

<p>This gives the right output</p>
