Java byte buffer getLong() overflows long variable
<p>I am working on a very bare bones ByteBuffer for use with java 1.4. I have a small skeleton that basically just have poor implementations of put/getInt() put/getLong(). My problem is that while putInt and getInt works, the getLong() (I think it is) is not working.</p>

<p>When I read out the fourth byte and shift that into the long it overflows. But all my variables are long so it should not overflow.</p>

<p>Heres the code (please bear in mind that this is just a start):</p>

<pre><code>public class ByteBuffer {

    private byte[] buffer;
    private int first = 0;
    private int last = 0;
    private int size;
    private int elements;

    public ByteBuffer(int size) {
        this.size = size;
        buffer = new byte[size];
    }

    public void putInt(int theInt) {
        for (int i = 0; i &lt; 4; i++) {
            put((byte) (theInt &gt;&gt;&gt; (8 * i)));
        }
    }

    public int getInt() {
        int theInt = 0;
        for (int i = 0; i &lt; 4; i++) {
            theInt |= (0xFF &amp; get()) &lt;&lt; (8 * i);
        }
        return theInt;
    }

    public void putLong(long theLong) {
        for (int i = 0; i &lt; 8; i++) {
            put((byte) (theLong &gt;&gt;&gt; (8 * i)));
        }
    }

    public long getLong() {
        long theLong = 0L;
        for (int i = 0; i &lt; 8; i++) {
            theLong |= (long) ((0xFF &amp; get()) &lt;&lt; (8 * i));
        }
        return theLong;
    }

    public void put(byte theByte) {
        buffer[last++] = theByte;
        if (last == size) {
            last = 0;
        }
        elements++;
    }

    public byte get() {
        byte theByte = buffer[first++];
        if (first == size) {
            first = 0;
        }
        elements--;
        return theByte;
    }

    public byte[] array() {
        return (byte[]) buffer.clone();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        ByteBuffer buff = new ByteBuffer(512);

        buff.putLong(9223372036854775807L);
        buff.putLong(-9223372036854775808L);

        System.out.println(9223372036854775807L);
        System.out.println(-9223372036854775808L);

        long l1 = buff.getLong();
        long l2 = buff.getLong();
        System.out.println(l1);
        System.out.println(l2);
    }

}
</code></pre>
