3

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?

Community
  • 1
  • 1
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • 1
    Don't know if you accidently missed it, but the so post from which you found out how to set a long specifies that it has to be : `long l = -1L;`. The L is there for a [reason](http://stackoverflow.com/questions/769963/javas-l-number-long-specification-question). Cheers – Daneo Nov 27 '12 at 07:26
  • @Daneo: `long l = -1;` and `long l =-1L;` produce **exactly** the same bytecode (http://pastie.org/5441210). There certainly *can* be times when you need the `L`, but not when you're assigning a literal `-1` to a `long`. Not to say it's not good practice. – T.J. Crowder Nov 27 '12 at 07:32
  • @T.J.Crowder Thanks for the clarification, and to confirm. It might not be necessary now, but just to prevent cases like [this](http://www.daniweb.com/software-development/java/threads/165728/why-long-variable-is-taking-integer-value) by not applying that practice. As that link says not applying the L makes it autoconvert, and that will work in the case the value fits the size of an int. I thought it'd be better not to rely on such. – Daneo Nov 27 '12 at 07:40
  • @Daneo: Agreed, always best to write it out. – T.J. Crowder Nov 27 '12 at 07:42
  • Updated my answer - always good to be explicit. – Adam Matan Nov 27 '12 at 07:54

2 Answers2

4

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

Is this assumption safe?

Yes, it's defined by the Java Language Specification, Section 4.2:

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

What you describe is how two's complement integer numbers work, -1 is "all bits on".

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875