1. 程式人生 > >輸入任意十進位制數字,轉換為任意進製表示

輸入任意十進位制數字,轉換為任意進製表示

次程式碼來源於 Integer 的原碼:在Integer 中的實現如下:

public class BinOctalHex {

    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        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); } static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
int charPos = len; int radix = 1 << shift; int mask = radix - 1; do { buf[offset + --charPos] = digits[val & mask]; 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' }; public static void main(String[] args){ //Java 演算法實現,來源於Integer /** * 第一個值:需要轉換的十進位制數字 * 第二個值: 1 二進位制 * 3 八進位制 * 4 十六進位制 */ String s = toUnsignedString0(15,3); System.out.println(s); } }