public static String toBinaryString(int i) {
return toUnsignedString(i, 1);
}
发现其实是调用了toUnsignedString(int i,int shift)方法,源代码如下:
private static String toUnsignedString(int i, int shift) {
char[] buf = new char[32];
int charPos = 32;
int radix = 1 << shift;
int mask = radix - 1;
do {
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
}
如果传入5,则返回101,怎么返回0000 0101呢?
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
JAVA]二进制,八进制,十六进制,十进制间进行相互转换:
http://blog.csdn.net/szwangdf/article/details/2601941