Search code examples
javaarraysbit-manipulationlong-integerfill

Does Java bitwise representation of long vary?


I would like to fill a Java array of longs, so that all of its bits are set to 1. I've found out that the corresponding long value is -1, or "0xFFFFFFFFFFFFFFFFl":

long l = -1L;
System.out.println(Long.toBinaryString(l));

"1111111111111111111111111111111111111111111111111111111111111111"

So I use Arrays.fill() to fill the array with 1's:

final long allBitsOn = -1L;
long[] bits = new long[arrayLength];
Arrays.fill(bits, allBitsOn);

This array is a fundamental infrastructure of a major project, and I want to be completely sure that long has 64 bits, and that long(-1) will always have all its bits set to 1, across all VM implementations and future versions of Java.

Is this assumption safe?


Solution

  • Yes, the assumption is safe. From the JLS:

    4.2. Primitive Types and Values

    The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).

    In two's complement, -1 is represented by the bit pattern consisting of all ones.