public static String toBinaryString(int i) {java
return toUnsignedString(i, 1);git
}數組
發現實際上是調用了toUnsignedString(int i,int shift)方法,源代碼以下:spa
private static String toUnsignedString(int i, int shift) {.net
char[] buf = new char[32];code
int charPos = 32;orm
int radix = 1 << shift;blog
int mask = radix - 1;get
do {string
buf[--charPos] = digits[i & mask];
i >>>= shift;
} while (i != 0);
return new String(buf, charPos, (32 - charPos));
}
其中digits的定義是:
final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
好了,源代碼都哦已經找好了,如今就看看代碼是怎麼實現功能的了,咱們舉toBinaryString(5)爲例,也就是toUnsignedString(5, 1);
private static String toUnsignedString(int i, int shift) {
char[] buf = new char[32];
int charPos = 32;
int radix = 1 << shift;//此處shift是1,左移的結果是0010
int mask = radix - 1;//而後減1,結果是0001
do {
buf[--charPos] = digits[i & mask];//buf[31]=digits[0101 & 0001]=digits[1]=1
i >>>= shift;
} while (i != 0);
//循環第二次:buf[30]=digits[0010 & 0001]=digits[0]=0
//循環第三次:buf[29]=digits[0001 & 0001]=digits[0]=1
return new String(buf, charPos, (32 - charPos));
//String(char[] value, int offset, int count) 分配一個新的 String,它包含取自字符數組參數一個子數組的字符。new String爲buf[29]+buf[30]+buf[31]=101
}
int to 8-bit binarystring:
byte b2 = (byte) 5; String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0'); System.out.println(s2); // 0000 0101