Java Integer.toOctalString()十进制转成八进制
java中Integer.toHexString()用于将十进制转成八进制输出。
定义
String toOctalString(int i) //以八进制(基数 8)无符号整数形式返回一个整数参数的字符串表示形式。
也就是将传入的数值十进制转成八进制
源码
public static String toOctalString(int i) { return toUnsignedString0(i, 3); } private static String toUnsignedString0(int val, int shift) { // assert shift > 0 && shift <=5 : "Illegal shift value"; //计算这个int转换成二进制后占多少bit(123-->>7) int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val); //用于确定最后生成的字符串有几个字符 int chars = Math.max(((mag + (shift - 1)) / shift), 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;//2^shift (此例子是2^4) int mask = radix - 1; //(16进制-->>15 8进制-->>7) do { //val&mask 相当于 val%(mask+1) 这里是 123%16 buf[offset + --charPos] = Integer.digits[val & mask]; val >>>= shift; } while (val != 0 && charPos > 0); return charPos; }
例子
public class IntegerToOctalStringDemo { public static void main(String[] args) { System.out.println("十进制转八进制:"+Integer.toOctalString(120)); } } 输出 十进制转八进制 :170
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。