package lookjob; public class App { 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' }; /*** * 進制轉換 * @param i 原始數值 * @param shift 二進制 1 八進制 3 十六進制 4 * @return */ public static String toUnsignedString(int i, int shift) { char[] buf = new char[32]; int charPos = 32; int radix = 1 << shift; int mask = radix - 1; do { buf[--charPos] = digits[i & mask]; i >>>= shift; } while (i != 0); return new String(buf, charPos, (32 - charPos)); } public static void main(String[] args) { //輸出17的十六進制表示 System.out.println(toUnsignedString(17,4)); } }
二進制意味着每位轉換一個 charjava
八進制意味着每3位轉換一個 chargit
十六進制意味着每4位轉換一個 charcode
經過it
int radix = 1 << shift; int mask = radix - 1;
mask 後尾數都爲1,而後class
i&mask
就可得到後n爲的值,最後經過 digits 獲取到對應的 char二進制