日期:2014-05-20  浏览次数:20764 次

给个16进制转化成10进制的算法?快,急用
给个16进制转化成10进制的算法

------解决方案--------------------
public class Change {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s=new String( "a ");
System.out.println(Long.parseLong(s,16));
}

}

------解决方案--------------------
仿照 Integer.parseInt() 方法做了一个 2~36 进制转换的代码,楼主可以参考一下:

public class Test {
  public static void main(String[] args) {    
    try {
      // 采用自己实现的方法
      System.out.println(toIntDecimal( "5a44e3 ", 16));
    }catch(Exception e){
      System.out.println( "ERROR: " + e.getMessage());
    }

    // Java 中内置的方法
    System.out.println(Integer.parseInt( "5a44e3 ", 16));
  }

  public static int toIntDecimal(String s, int radix) throws Exception {
    String seq = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
    s = s.trim();
    if(s.length() > (int)((Math.log(Integer.MAX_VALUE)+1.0) / Math.log(radix))){
      throw new Exception( s + " 数值溢出,无法转换 ");
    }    
    if( (radix > seq.length()) || (radix < 2)){
      throw new Exception( "无法转换进制 " + radix);
    }    
    int num = 0;
    for (int i = 0; i < s.length(); i++) {
      int idx = seq.indexOf(Character.toUpperCase(s.charAt(i)));
      if( (idx > radix - 1) || (idx < 0) ) {
        throw new Exception( s + " 中出现非法字符 " + s.charAt(i));
      }
      num = idx + (num * radix);
    }
    return num;
  }
}