Why are there no binary literals in Java?

后端 未结 6 915
花落未央
花落未央 2020-12-17 09:15

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

相关标签:
6条回答
  • 2020-12-17 09:39

    Java 7 includes it.Check the new features.

    Example:

    int binary = 0b1001_1001;
    
    0 讨论(0)
  • 2020-12-17 09:42

    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.

    0 讨论(0)
  • 2020-12-17 09:50

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

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

    0 讨论(0)
  • 2020-12-17 09:50

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

    0 讨论(0)
  • 2020-12-17 09:53

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

    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".

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

    int yourInteger = Integer.parseInt("100100101", 2);
    
    0 讨论(0)
  • 2020-12-17 09:58

    actually, it is. in java7.

    http://code.joejag.com/2009/new-language-features-in-java-7/

    0 讨论(0)
提交回复
热议问题