Java SE 7中, 整数类型(byte
, short
, int
以及long
) 也可以使用二进制数系来表示。要指定一个二进制字面量,可以给二进制数字添加前缀 0b
或者 0B
。下面的示例展示了一些二进制字面量:
// 一个8位的'byte'值: byte aByte = (byte)0b00100001; // 一个16位的'short'值: short aShort = (short)0b1010000101000101; // 几个32位的'int'值: int anInt1 = 0b10100001010001011010000101000101; int anInt2 = 0b101; int anInt3 = 0B101; // B可以是大写或者小写. // 一个64位的'long'值.注意"L"后缀: long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;
相比于十六进制或者八进制,二进制字面量可以使数据之间的关系更加清晰。比如, 下面数组中的每个后续数字是按位旋转的:
public static final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001, 0b00010011, 0b00100110, 0b01001100, 0b10011000 }
十六进制中, 数字之间的关系并不清晰:
public static final int[] phases = { 0x31, 0x62, 0xC4, 0x89, 0x13, 0x26, 0x4C, 0x98 }
可以在代码中使用二进制字面量常量来验证一个规范文档, 比如一个针对假设的8位微处理器的模拟器:
public State decodeInstruction(int instruction, State state) { if ((instruction & 0b11100000) == 0b00000000) { final int register = instruction & 0b00001111; switch (instruction & 0b11110000) { case 0b00000000: return state.nop(); case 0b00010000: return state.copyAccumTo(register); case 0b00100000: return state.addToAccum(register); case 0b00110000: return state.subFromAccum(register); case 0b01000000: return state.multiplyAccumBy(register); case 0b01010000: return state.divideAccumBy(register); case 0b01100000: return state.setAccumFrom(register); case 0b01110000: return state.returnFromCall(); default: throw new IllegalArgumentException(); } } else { final int address = instruction & 0b00011111; switch (instruction & 0b11100000) { case 0b00100000: return state.jumpTo(address); case 0b01000000: return state.jumpIfAccumZeroTo(address); case 0b01000000: return state.jumpIfAccumNonzeroTo(address); case 0b01100000: return state.setAccumFromMemory(address); case 0b10100000: return state.writeAccumToMemory(address); case 0b11000000: return state.callTo(address); default: throw new IllegalArgumentException(); } } }
可以使用二进制字面量增强位图的可读性:
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 }
本文翻译自Oracle官方文档http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html,如有不正确的地方,敬请指正,谢谢!