問題描述
類似于如何用十六進(jìn)制或八進(jìn)制定義整數(shù)常量,我可以用二進(jìn)制來定義嗎?
Similar to how you can define an integer constant in hexadecimal or octal, can I do it in binary?
我承認(rèn)這是一個非常簡單(而且很愚蠢)的問題.我的谷歌搜索結(jié)果是空的.
I admit this is a really easy (and stupid) question. My google searches are coming up empty.
推薦答案
因此,隨著 Java SE 7 的發(fā)布,二進(jìn)制表示法成為開箱即用的標(biāo)準(zhǔn).如果你對二進(jìn)制有很好的理解,語法就非常簡單明了:
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;
特別是在將類級別變量聲明為二進(jìn)制文件這一點上,使用二進(jìn)制表示法初始化靜態(tài)變量也絕對沒有問題:
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;
注意不要用太多數(shù)據(jù)溢出數(shù)字,否則你會得到一個編譯器錯誤:
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
現(xiàn)在,如果您真的想變得花哨,您可以將 Java 7 中另一個被稱為數(shù)字文字的簡潔新功能與下劃線結(jié)合起來.看看這些帶有文字下劃線的二進(jìn)制符號的奇特示例:
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;
現(xiàn)在不是很好很干凈,更不用說高度可讀了嗎?
Now isn't that nice and clean, not to mention highly readable?
我從我在 TheServerSide 上寫的一篇關(guān)于該主題的小文章中提取了這些代碼片段.請隨時查看以獲取更多詳細(xì)信息:
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 和二進(jìn)制表示法:掌握 OCP Java 程序員 (OCPJP) 考試
這篇關(guān)于在Java中,我可以用二進(jìn)制格式定義一個整數(shù)常量嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!