38

I want to declare my integer number by a binary literal. Is it possible in Java?

0

2 Answers 2

50

In JDK 7 it is possible:

int binaryInt = 0b101;

Just prefix your number with 0b.

Sign up to request clarification or add additional context in comments.

1 Comment

Got an exercise problem using this syntax and just found out about it. See also chapter 3.10.1 in the JLS for the exact syntax and some examples.
46

Starting with Java 7 you can represent integer numbers directly as binary numbers, using the form 0b (or 0B) followed by one or more binary digits (0 or 1). For example, 0b101010 is the integer 42. Like octal and hex numbers, binary literals may represent negative numbers.

If you do not have Java 7 use this:

int val = Integer.parseInt("001101", 2);

There are other ways to enter integer numbers:

  1. As decimal numbers such as 1995, 51966. Negative decimal numbers such as -42 are actually expressions consisting of the integer literal with the unary negation operation.

  2. As octal numbers, using a leading 0 (zero) digit and one or more additional octal digits (digits between 0 and 7), such as 077. Octal numbers may evaluate to negative numbers; for example 037777777770 is actually the decimal value -8.

  3. As hexadecimal numbers, using the form 0x (or 0X) followed by one or more hexadecimal digits (digits from 0 to 9, a to f or A to F). For example, 0xCAFEBABEL is the long integer 3405691582. Like octal numbers, hexadecimal literals may represent negative numbers.

More details can be found in this Wikibook.

2 Comments

+1 you can double literals in hexi-decmal. See the source for Double for examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.