paint-brush
Java bits: 0xFF and 0xFFLby@eric.liu.developer
2,682 reads
2,682 reads

Java bits: 0xFF and 0xFFL

by ericliuOctober 31st, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

I wrote a method to read a long typed number from an InputStream. The code is as follows:
featured image - Java bits: 0xFF and 0xFFL
ericliu HackerNoon profile picture

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.


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;}