在 Java SE 7 中,整數型態(byte
、short
、int
以及 long
)可以用二進位數字系統來表示,它的前置詞是 0b
或 0B
。下面列出幾個用法:
// 8-bit byte value
byte b = (byte) 0b10000001;
// 16-bit short value
short s = (short) 0b1000000110000001;
// 32-bit int value
int i = 0b10100001010001011010000101000101;
int j = 0B1000;
// 64-bit long value with the L suffix
long x = 0b00101100110101101011011011001001011101001010L;
有的時候,數字用二進位法來表示,會比八或十六進位來得清楚和易讀。舉例來說:
// Before
private static byte[] unmask = {
(byte) 0xFE,
(byte) 0xFD,
(byte) 0xFB,
(byte) 0xF7,
(byte) 0xEF,
(byte) 0xDF,
(byte) 0xBF,
(byte) 0x7F
};
// After
private static byte[] unmask = {
(byte) 0b11111110,
(byte) 0b11111101,
(byte) 0b11111011,
(byte) 0b11110111,
(byte) 0b11101111,
(byte) 0b11011111,
(byte) 0b10111111,
(byte) 0b01111111
};
原本在 Java 語言中可以使用整數數字的地方,都可以用二進位表示法:
if ((flag & 0b00001111) >= 0b00000001) {
switch (b) {
case 0b00000011: return “foo”;
case 0b10101001: return “bar”;
}
}
你也可以用它來設計迷宮陣列,或是點陣圖形的表情符號,像是下面這個笑臉圖:
public static final short[] HAPPY_FACE = {
(short)0b0000011111100000;
(short)0b0000100000010000;
(short)0b0001000000001000;
(short)0b0010000000000100;
(short)0b0100000000000010;
(short)0b1000011001100001;
(short)0b1000011001100001;
(short)0b1000000000000001;
(short)0b1000000000000001;
(short)0b1001000000001001;
(short)0b1000100000010001;
(short)0b0100011111100010;
(short)0b0010000000000100;
(short)0b0001000000001000;
(short)0b0000100000010000;
(short)0b0000011111100000;
}