【位運算】如何優雅地將進制數轉換?

理論

  • 二進制數字中某位的權重:2N12^{N - 1 } 次方,N 爲該位所在的位數。
  • 二進制轉十進制:數字中所有位 × 本位的權重然後求和。

實踐

用輪子

好了看了那麼多理論,是需要實踐來鞏固一下得了:

public class 十進制與各進制的相互轉換 {
  public static void main(String[] args){
    int decimal = 10;
    System.out.println("十進制數:"+decimal+",轉換爲二進制:"+Integer.toBinaryString(decimal));
    System.out.println("十進制數:"+decimal+",轉換爲八進制:"+Integer.toOctalString(decimal));
    System.out.println("十進制數:"+decimal+",轉換爲十六進制:"+Integer.toHexString(decimal));
    
    System.out.println("二進制數:"+"1010" +",轉換爲十進制:"+Integer.valueOf("1010", 2));
    System.out.println("八進制數:"+"12" +",轉換爲十進制:"+Integer.valueOf("12", 8));
    System.out.println("十六進制數:"+"a" +",轉換爲十進制:"+Integer.valueOf("a", 16));
  }
}
十進制數:10,轉換爲二進制:1010
十進制數:10,轉換爲八進制:12
十進制數:10,轉換爲十六進制:a
二進制數:1010,轉換爲十進制:10
八進制數:12,轉換爲十進制:10
十六進制數:a,轉換爲十進制:10

造輪子

  • 二進制數:1010
    十進制數:123+022+121+020=8+0+2+0=101*2^3 + 0*2^2 + 1*2^1 + 0*2^0 = 8 + 0 + 2 +0 = 10
public int binaryToDecimal(String S){
  int x = 0;
  int mul = 1;
  for(int i = S.length()-1; i > 0; i--){
      x += mul * (S.charAt(i)=='1' ? 1 : 0);
      mul *= 2;
  }
  return mul;
}
String radix = "1010";
public int method(String S){
  int x = 0;
  for (char c : S.toCharArray())
      x = x*2 + (c == '1' ? 1 : 0);
  return x;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章