Similar to how you can define an integer constant in hexadecimal or octal, can I do it in binary?
I admit this is a really easy (and stupid) question. My google sea
The answer from Ed Swangren
public final static long mask12 =
Long.parseLong("00000000000000000000100000000000", 2);
works fine. I used long
instead of int
and added the modifiers to clarify possible usage as a bit mask. There are, though, two inconveniences with this approach.
I can suggest alternative approach
public final static long mask12 = 1L << 12;
This expression makes it obvious that the 12th bit is 1 (the count starts from 0, from the right to the left); and when you hover mouse cursor, the tooltip
long YourClassName.mask12 = 4096 [0x1000]
appears in Eclipse. You can define more complicated constants like:
public final static long maskForSomething = mask12 | mask3 | mask0;
or explicitly
public final static long maskForSomething = (1L<<12)|(1L<<3)|(1L<<0);
The value of the variable maskForSomething
will still be available in Eclipse at development time.