public class Test {
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' };
public static void main(String[] args) {
System.out.println(Test.toBinaryString(15));
System.out.println(Test.toHexString(15));
System.out.println(Test.toOctalString(15));
}
public static String toBinaryString(int i) {
return toUnsignedString(i, 1);
}
public static String toHexString(int i) {
return toUnsignedString(i, 4);
}
public static String toOctalString(int i) {
return toUnsignedString(i, 3);
}
private static String toUnsignedString(int i, int shift) {
char[] buf = new char[32]; //int转成二进制最多32位,转成其它进制则更少了
int charPos = 32; //记录数组下标
int radix = 1 << shift; //基数
int mask = radix - 1; //掩码,如16进制相当于4位2进制
do {
buf[--charPos] = digits[i & mask]; //用掩码逐次转成其它进制
i >>>= shift;
} while (i != 0);
return new String(buf, charPos, (32 - charPos)); //转成字符串
}
}
输出结果:
1111
f
17
PS:其实是JDK里面的Integer源代码,我把它抽出来做笔试面试用。