该方法作用为将传入数值转换为规定进制,并且返回该进制数的字符串, Integer类中的十进制转换为各种进制都是调用的这个方法实现的。这里用二进制来举例 val为传入数据 shift为log2(所需进制数)例如要转换为二进制则shift=log2(2)=1;
源码如下
private static String toUnsignedString0(int val, int shift) { int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val); int chars = Math.max(((mag + (shift - 1)) / shift), 1); if (COMPACT_STRINGS) { byte[] buf = new byte[chars]; formatUnsignedInt(val, shift, buf, 0, chars); return new String(buf, LATIN1); } else { byte[] buf = new byte[chars * 2]; formatUnsignedIntUTF16(val, shift, buf, 0, chars); return new String(buf, UTF16); } }注释如下
private static String toUnsignedString0(int val, int shift) { /*Integer.numberOfLeadingZeros(val);作用为返回无符号整型i的 最高非零位前面的0的个数,包括符号位在内。==所以mag为val的二 进制有效位数*/ int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val); /*==chars表示的是var转换为1<<shift进制后的长度====要达到这种效果 只需要mag/shift并向上取整便可达成,但因为int类型数据是向下取整所 以采用((mag + (shift - 1))/shift虽然我写不出来这种算式,但确实可 以达到这种效果*/== int chars = Math.max(((mag + (shift - 1)) / shift), 1); /*java9之后,为了节省字符串的空间,默认开启字符串压缩,也就是用 byte(8位)保存字母。COMPACT_STRINGS默认开启。coder由两个值: LATIN1,UTF16。UTF16是肯定没有开启压缩的。*/ //COMPACT_STRINGS默认为true即使用的LATIN1 if (COMPACT_STRINGS) { byte[] buf = new byte[chars]; //该方法就是将val的(1<<shift)进制存到byte[]里 formatUnsignedInt(val, shift, buf, 0, chars); return new String(buf, LATIN1); } else { byte[] buf = new byte[chars * 2]; formatUnsignedIntUTF16(val, shift, buf, 0, chars); return new String(buf, UTF16); } }