private static String toUnsignedString0(int val, int shift) { // assert shift > 0 && shift <=5 : "Illegal shift value"; int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);// 32-前导0的个数,有数值的位数 int chars = Math.max(((mag + (shift - 1)) / shift), 1);// 需要的字符数组的长度=除数+1,此处取巧,先+1,保证即使除不尽也是满足数组长度 char[] buf = new char[chars]; formatUnsignedInt(val, shift, buf, 0, chars); // Use special constructor which takes over "buf". return new String(buf, true); }
static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) { int charPos = len; int radix = 1 << shift;// 进制,如 1 << 3 = 8 int mask = radix - 1;// 掩码,如8-1=7= 00000000 00000000 0000000 00000111 do { buf[offset + --charPos] = Integer.digits[val & mask];// 2进制低位 排在 字符数值高位 val >>>= shift; } while (val != 0 && charPos > 0); return charPos; } 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' };