88

Similar to how you can define an integer constant in hexadecimal or octal, can I do it in binary?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Aaron Fi
  • 10,116
  • 13
  • 66
  • 91
  • 2
    Just FYI, in pretty much every programming language, the idiom is to write binary constants in hex, and not the actual binary string. – abyx Nov 07 '09 at 13:07
  • 3
    Right, but I imagine that's because hex is the closest thing available, not because there's something wrong with binary. In languages I've used that do support binary literals, I don't think the convention is to ignore this feature. – Ken Jul 10 '10 at 21:29
  • 1
    https://docs.oracle.com/javase/8/docs/technotes/guides/language/binary-literals.html – user3136131 Jun 16 '16 at 10:59
  • Year 2017: the accepted answer must be that provided by Russ. See: https://stackoverflow.com/a/1692932/716079 – Lourenco Aug 15 '17 at 19:53

8 Answers8

155

In Java 7:

int i = 0b10101010;

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

Russ Hayward
  • 5,617
  • 2
  • 25
  • 30
  • 33
    I'd also like to point out there can be `_` characters to make the sequence more readable: `int i = 0b1010_1010_0011;` – user12345613 Mar 08 '12 at 20:19
  • @Russ What does 0b signify here ? What is this feature called in Java 7 ? – Geek Aug 23 '12 at 08:22
  • 1
    0b signifies binary. The feature is called binary literals: http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html – Russ Hayward Aug 23 '12 at 15:07
  • 1
    Love this new representation of binary data. The String representation would be very hard to read. Look at the difference of the accepted answer and the one from "@user12345613". +1 for him. – Marcello DeSales Nov 12 '13 at 20:10
70

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:

byte fourTimesThree = 0b1100;
byte data = 0b0000110011;
short number = 0b111111111111111; 
int overflow = 0b10101010101010101010101010101011;
long bow = 0b101010101010101010101010101010111L;

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:

public static final int thingy = 0b0101;

Just be careful not to overflow the numbers with too much data, or else you'll get a compiler error:

byte data = 0b1100110011; // Type mismatch: cannot convert from int to byte

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:

int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011;
long bow = 0b1__01010101__01010101__01010101__01010111L;

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

Cameron McKenzie
  • 3,684
  • 32
  • 28
  • 3
    Why is your byte data = 0b0000110011; has 10 bits? I'm new at programming but I think it should looks like 0b00110011 to fit 8 bits of byte data type. – Mike Aug 24 '14 at 10:50
  • 1
    For anybody wondering the same as Mike, it's because the compiler converts it to the number it represents - you could have tens of leading zeroes and they won't affect the actual value. The compilation process is essentially the same as if you had wrote a decimal there. – Luke Briggs Jan 31 '17 at 05:14
  • 1
    by definition primitive type byte can store 256 numbers between -128 to 127( -128 to -1 & 0 to 127 ). But how to represent -128 using a binary literal. for e.g. byte b = -0b1111111; denotes -127 but what about -128 ? – nirmalsingh Oct 29 '17 at 14:59
54

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 S.
  • 122,712
  • 22
  • 185
  • 265
  • 1
    Amongst other uses, the stippling pattern for line and polygon rasterization is specified as an integer in several popular graphics libraries. Using parseInt or parseShort allow the developer to easily visualize the pattern. – charstar Feb 12 '11 at 06:36
  • 5
    Since Java 7, Russ Hayward's answer is the correct answer. Prior to Java 7, you can use an online tool or your favorite calculator to convert binary to one of the notations recognized by old Java versions (octal, decimal, or hexadecimal). If another radix is used, a descriptive comment containing the binary representation can be placed at the declaration to clarify the value for readers. – Jason C Nov 20 '13 at 01:19
  • This is a rather dirty solution, isn't it? You're just taking 16 bytes to represent 1 byte (not counting the second argument and the conversion). Of course, unless the compiler optimises this, which I doubt. – Tomáš Zato Apr 24 '14 at 23:20
  • @TomášZato: Yes, it is, but what solution would you suggest given that the language did not support binary literals when I wrote this answer? Russ Hayward should have the accepted answer now. – Ed S. Apr 25 '14 at 18:38
  • I would suggest giving up the comfort and use integers. In the variable definition itself, it's ok, but this answer might motivate users to use this approach for loops, etc. And generally, I think programmer should try to give up his own comfort for some performance. – Tomáš Zato Apr 25 '14 at 21:00
  • @TomášZato: So would I, and I said as much in my answer. – Ed S. Apr 25 '14 at 22:55
  • Year 2017: Fortunately there is notation for binary representation. It begins with "0b". Example: `byte b = 0b01000001` (for a better readness `byte b = 0b0100_0001`). – Lourenco Aug 15 '17 at 19:51
18

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
  • 281
  • 1
  • 3
  • 6
18

Using binary constants to masking

Declare constants:

public static final int FLAG_A = 1 << 0;
public static final int FLAG_B = 1 << 1;
public static final int FLAG_C = 1 << 2;
public static final int FLAG_D = 1 << 3;

and use them

if( (value & ( FLAG_B | FLAG_D )) != 0){
    // value has set FLAG_B and FLAG_D
}
pawelzieba
  • 16,082
  • 3
  • 46
  • 72
12

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
  • 2,858
  • 22
  • 21
2

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;
sth
  • 222,467
  • 53
  • 283
  • 367
Anthony Hayward
  • 2,164
  • 21
  • 17
0

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"

PhiLho
  • 40,535
  • 6
  • 96
  • 134
NSherwin
  • 184
  • 1
  • 10