views:

2495

answers:

6

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.

+11  A: 

There are no binary literals in Java, but I suppose that you could do this (though I don't see the point):

int a = Integer.parseInt("10101010", 2);
Ed Swangren
+5  A: 

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:

int i = 0xcafe ; // hexadecimal case
int j = 045 ;    // octal case
int l = 42 ;     // decimal case
Pierre
+1  A: 

Slightly more awkward answer:

public class Main {

    public static void main(String[] args) {
     byte b = Byte.parseByte("10", 2);
        Byte bb = new Byte(b);
        System.out.println("bb should be 2, value is \"" + bb.intValue() + "\"" );
    }

}

which outputs [java] bb should be 2, value is "2"

NSherwin
+3  A: 

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.

  1. The direct typing of all those zeroes is error prone
  2. The result is not available in decimal or hex format at the time of development

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.

chgman
+8  A: 

In Java 7:

int i = 0b10101010;

There are no binary literals in older versions of Java (see other answers for alternatives).

Russ Hayward
+1  A: 

If you want to mess around with lots of binary you could define some constants:

public static final int BIT_0 = 0x00000001;
public static final int BIT_1 = 0x00000002;

etc.

or

public static final int B_00000001 = 0x00000001;
public static final int B_00000010 = 0x00000002;
public static final int B_00000100 = 0x00000004;
Ant