Are there binary literals in Java?

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

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

回答1:

Look at this link:

http://en.wikibooks.org/wiki/Java_Programming/Literals/Numeric_Literals/Integer_Literals

In Java, you may enter integer numbers in several formats:

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.

4) Starting in J2SE 7.0, 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 J2SE 7.0 use this:

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


回答2:

In JDK 7 it is possible:

int binaryInt = 0b101; 

Just prefix your number with 0b.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!