在Java中,我可以定义为二进制格式的整型常量? [英] In Java, can I define an integer constant in binary format?
问题描述
要如何定义一个整数十六进制或八进制常数相似,我可以做的二进制?
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的发布,二进制记数法标配开箱。语法是相当简单和明显的,如果你有二进制体面的理解:
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 byte
现在,如果你真的想获得幻想,你可以在被称为用下划线数字文字Java 7的结合,其他整齐的新功能。看看二进制符号与文字下划线的这些花哨的例子:
Now, 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?
我从一个小文章,我写了一篇关于在的TheServerSide的话题拉扯了这些code片段。随时检查出来的更多详细信息:
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和二进制表示法:掌握OCP Java程序员(OCPJP)考试
这篇关于在Java中,我可以定义为二进制格式的整型常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!