I wrote a method to read a long typed number from an InputStream. The code is as follows:
Company Mentioned
Some Random Binaries
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.