类似于如何以十六进制或八进制定义整数常量,我可以用二进制代码吗?
我承认这是一个很简单(和愚蠢的)问题。 我的谷歌搜索是空的。
Similar to how you can define an integer constant in hexadecimal or octal, can I do it in binary?
I admit this is a really easy (and stupid) question. My google searches are coming up empty.
最满意答案
所以,随着Java SE 7的发布,二进制符号是标准的开箱即用。 如果您对二进制文件有一个正确的理解,那么语法是非常简单的:
byte fourTimesThree = 0b1100; byte data = 0b0000110011; short number = 0b111111111111111; int overflow = 0b10101010101010101010101010101011; long bow = 0b101010101010101010101010101010111L;具体来说,将类级别变量声明为二进制文件,使用二进制符号初始化静态变量绝对没有问题:
public static final int thingy = 0b0101;只要注意不要用太多的数据溢出数字,否则你会得到一个编译错误:
byte data = 0b1100110011; // Type mismatch: cannot convert from int to byte现在,如果你真的想得到喜好,你可以将Java 7中的另一个整洁的新功能与数字文字和下划线组合在一起。 看看这些具有文字下划线的二进制符号的奇特例子:
int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011; long bow = 0b1__01010101__01010101__01010101__01010111L;现在不是那么好干净,更不用说高可读性?
我从TheServerSide中的一篇关于该主题的小文章中提取了这些代码段。 随时查看更多详情:
Java 7和二进制符号:掌握OCP Java程序员(OCPJP)考试
So, with the release of Java SE 7, binary notation comes standard out of the box. The syntax is quite straight forward and obvious if you have a decent understanding of binary:
byte fourTimesThree = 0b1100; byte data = 0b0000110011; short number = 0b111111111111111; int overflow = 0b10101010101010101010101010101011; long bow = 0b101010101010101010101010101010111L;And specifically on the point of declaring class level variables as binaries, there's absolutely no problem initializing a static variable using binary notation either:
public static final int thingy = 0b0101;Just be careful not to overflow the numbers with too much data, or else you'll get a compiler error:
byte data = 0b1100110011; // Type mismatch: cannot convert from int to byteNow, if you really want to get fancy, you can combine that other neat new feature in Java 7 known as numeric literals with underscores. Take a look at these fancy examples of binary notation with literal underscores:
int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011; long bow = 0b1__01010101__01010101__01010101__01010111L;Now isn't that nice and clean, not to mention highly readable?
I pulled these code snippets from a little article I wrote about the topic over at TheServerSide. Feel free to check it out for more details:
Java 7 and Binary Notation: Mastering the OCP Java Programmer (OCPJP) Exam
更多推荐
发布评论