paint-brush
Java bits: 0xFF and 0xFFL by@eric.liu.developer
2,736 reads
2,736 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:

Company Mentioned

Mention Thumbnail
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.


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;}
바카라사이트 바카라사이트 온라인바카라