Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there binary literals in Java?

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

like image 663
Conscious Avatar asked Jun 09 '12 12:06

Conscious


People also ask

Is binary used in Java?

Java 7 introduced the binary literal. It simplified binary number usage.

How do you do binary in Java?

To convert decimal to binary, Java has a method “Integer. toBinaryString()”. The method returns a string representation of the integer argument as an unsigned integer in base 2.

What is byte literal in Java?

You can use a byte literal in Java... sort of. byte f = 0; f = 0xa; 0xa (int literal) gets automatically cast to byte. It's not a real byte literal (see JLS & comments below), but if it quacks like a duck, I call it a duck.

What is hexadecimal literal in Java?

A hexadecimal integer literal begins with the 0 digit followed by either an x or X, followed by any combination of the digits 0 through 9 and the letters a through f or A through F. The letters A (or a) through F (or f) represent the values 10 through 15, respectively.


2 Answers

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.

like image 86
Bobs Avatar answered Sep 17 '22 18:09

Bobs


In JDK 7 it is possible:

int binaryInt = 0b101; 

Just prefix your number with 0b.

like image 20
Petar Minchev Avatar answered Sep 19 '22 18:09

Petar Minchev