java 为什么Java中没有二进制文字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4013441/
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-30 04:22:55  来源:igfitidea点击:

Why are there no binary literals in Java?

java

提问by Adrian M

Is there any particular reason why this kind of literal is not included whereas hex and octal formats are allowed?

为什么不包括这种文字,而允许使用十六进制和八进制格式,有什么特别的原因吗?

回答by Emil

Java 7 includes it.Check the new features.

Java 7 包括它。检查新功能

Example:

例子:

int binary = 0b1001_1001;

回答by aioobe

Binary literals were introduced in Java 7. See "Improved Integer Literals":

二进制文字是在 Java 7 中引入的。请参阅“改进的整数文字”

int i = 0b1001001;

The reason for not including them from day one is most likely the following: Java is a high-level language and has been quite restrictive when it comes to language constructs that are less important and low level. Java developers have had a general policy of "if in doubt, keep it out".

从第一天起就没有包括它们的原因很可能如下:Java 是一种高级语言,在涉及不太重要和低级的语言结构时,它受到了很大的限制。Java 开发人员有一个“如有疑问,请将其排除”的一般策略。

If you're on Java 6 or older, your best option is to do

如果您使用的是 Java 6 或更旧版本,最好的选择是

int yourInteger = Integer.parseInt("100100101", 2);

回答by endarkened

回答by Frédéric Hamidi

The associated bugis open since April 2004, has low priority and is considered as a request for enhancement by Sun/Oracle.

相关的bug是开放的自2004年4月,具有低优先级,被认为是由Sun / Oracle的增强申请。

I guess they think binary literals would make the language more complex and doesn't provide obvious benefits...

我猜他们认为二进制文字会使语言更复杂,并且不会提供明显的好处......

回答by user207421

There seems to be an impression here that implementing binary literals is complex. It isn't. It would take about five minutes. Plus the test cases of course.

这里似乎给人的印象是实现二进制文字很复杂。不是。大约需要五分钟。当然还有测试用例。

回答by user1639637

Java 7 does allow binary literals ! Check this: int binVal = 0b11010; at this link: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Java 7 确实允许二进制文字!检查这个: int binVal = 0b11010; 在此链接:http: //docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html