Integer源碼 轉2進位轉16進位

來源:互聯網
上載者:User

標籤:blog   os   java   ar   2014   sp   log   amp   c   


其中有一個私人方法,toUnsignedString(int i, int shift) 是為 
 public static String toHexString(int i) {
        return toUnsignedString(i, 4);
 }
public static String toBinaryString(int i) {
        return toUnsignedString(i, 1);
 }
著兩個方法服務的。

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'    }; private 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));    }
以559轉為16進位為例:

559 二進位位 10 0010 1111;

toUnsignedString(i, 4);
1.取4位計算對應的16進位字元;
2.然後右移4位,前面補0;
重複1 ,2;
----------
mask = 15,對應 1111;

          10 0010 1111 & mask = 1111 -> 15 -> digits[15] -> f;
右移4位後 00 0010 0010 & mask = 0010 -> 2 -> digits[2] -> 2;
右移4位後 00 0000 0010 & mask = 0010 -> 2 -> digits[2] -> 2; 

----> 22f

同樣如果轉為8進位則為:toUnsignedString(i, 3);

感覺自己寫的演算法都弱爆了

Integer源碼 轉2進位轉16進位

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.