java Java中有二进制文字吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10961091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:13:50  来源:igfitidea点击:

Are there binary literals in Java?

javasyntaxbinaryliterals

提问by Conscious

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

我想用二进制文字声明我的整数。在Java中可能吗?

回答by Bobs

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, 0b101010is the integer 42. Like octal and hex numbers, binary literals may represent negative numbers.

从 Java 7 开始,您可以将整数直接表示为 binary numbers,使用形式0b(or 0B) 后跟一个或多个二进制数字(0 或 1)。例如,0b101010是整数 42。与八进制数和十六进制数一样,二进制文字可以表示负数。

If you do not have Java 7 use this:

如果您没有 Java 7,请使用以下命令:

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 -42are 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 037777777770is 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, 0xCAFEBABELis the long integer 3405691582. Like octal numbers, hexadecimal literals may represent negative numbers.

  1. 作为十进制数,如1995, 51966。负十进制数,例如-42实际上是由带有一元否定运算的整数文字组成的表达式。

  2. 作为八进制数,使用前导 0(零)数字和一个或多个附加八进制数字(0 到 7 之间的数字),例如 077。八进制数可能计算为负数;例如037777777770实际上是十进制值-8。

  3. 作为十六进制数,使用形式 0x(或 0X)后跟一个或多个十六进制数字(数字从 0 到 9、a 到 f 或 A 到 F)。例如,0xCAFEBABEL长整数 3405691582。与八进制数一样,十六进制文字可以表示负数。

More details can be found in this Wikibook.

可以在此 Wikibook 中找到更多详细信息。

回答by Petar Minchev

In JDK 7 it is possible:

在 JDK 7 中是可能的:

int binaryInt = 0b101;

Just prefix your number with 0b.

只需在您的号码前加上0b