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 searches are coming up empty.
|
There are no binary literals in Java, but I suppose that you could do this (though I don't see the point):
|
|||||
|
In Java 7:
There are no binary literals in older versions of Java (see other answers for alternatives). |
|||||||||
|
The answer from Ed Swangren
works fine. I used
I can suggest alternative approach
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
appears in Eclipse. You can define more complicated constants like:
or explicitly
The value of the variable |
||||
|
Search for "Java literals syntax" on Google and you come up with some entries. There is an octal syntax (prefix your number with 0), decimal syntax and hexadecimal syntax with a "0x" prefix. But no syntax for binary notation. Some examples:
|
|||
|
So, with the release of Java SE 7, binary notation comes standard out of the box. The syntax is quite straight forward and obvious if you have a decent understanding of binary:
And specifically on the point of declaring class level variables as binaries, there's absolutely no problem initializing a static variable using binary notation either:
Just be careful not to overflow the numbers with too much data, or else you'll get a compiler error:
Now, if you really want to get fancy, you can combine that other neat new feature in Java 7 known as numeric literals with underscores. Take a look at these fancy examples of binary notation with literal underscores:
Now isn't that nice and clean, not to mention highly readable? I pulled these code snippets from a little article I wrote about the topic over at TheServerSide. Feel free to check it out for more details: Java 7 and Binary Notation: Mastering the OCP Java Programmer (OCPJP) Exam |
|||
|
Using binary constants to maskingDeclare constants:
and use them
|
|||
|
Slightly more awkward answer:
which outputs [java] bb should be 2, value is "2" |
||||
|
If you want to mess around with lots of binary you could define some constants:
etc. or
|
||||
|