I wrote a method to read a long typed number from an InputStream. The code is as follows:

public static long readLong(final ByteArrayInputStream inputStream) {

long n = 0L;

n |= ((inputStream.read() & 0xFF) << 0);

n |= ((inputStream.read() & 0xFF) << 8);

n |= ((inputStream.read() & 0xFF) << 16);

n |= ((inputStream.read() & 0xFF) << 24);

n |= ((inputStream.read() & 0xFF) << 32);

n |= ((inputStream.read() & 0xFF) << 40);

n |= ((inputStream.read() & 0xFF) << 48);

n |= ((inputStream.read() & 0xFF) << 56);

return n;

}

It returns wrong results and I was scratching my head around what went wrong.

After digging into it, I found that the method java.io.InputStream#read() returns an int type. When a very big left bit shift(like << 32)is performed on an int, the bits will go over bound and the high bits will be discarded.

The solution is to use a long type 0xFFL when we are performing the & operation on an int while hoping to get a long type as the result of such operations:

i & 0xFFL

The programme will perform a **sign extension** on i and keep all the bits.

**Sign extension - Wikipedia**

*Sign extension is the operation, in computer arithmetic, of increasing the number of bits of a binary number while…*en.wikipedia.org

So the correct code should look as follows:

public static long readLong(final ByteArrayInputStream inputStream) {

long n = 0L;

n |= ((inputStream.read() & 0xFFL) << 0);

n |= ((inputStream.read() & 0xFFL) << 8);

n |= ((inputStream.read() & 0xFFL) << 16);

n |= ((inputStream.read() & 0xFFL) << 24);

n |= ((inputStream.read() & 0xFFL) << 32);

n |= ((inputStream.read() & 0xFFL) << 40);

n |= ((inputStream.read() & 0xFFL) << 48);

n |= ((inputStream.read() & 0xFFL) << 56);

return n;

}