十六进制字符转成整数

源代码

package 十六进制字符转成整数;

/**
 * @author 邓雪松 (づ ̄ 3 ̄)づ)
 * @create 2021-10-20-16-41
 */
public class Demo {
    public static void main(String[] args) {
        String hex = "111A";
        int tmp = hex2Int(hex);
        if(tmp != -1){
            System.out.println(hex2Int(hex));
        }else{
            System.out.println("包含非十六进制字符!!!");
        }
    }
    /**
     * 获取十六进制ch的int值,如A:10,F:15,9:9
     */
    public static int getHexValue(char ch){
        if(ch>='0'&&ch<='9'){
            return Integer.parseInt(String.valueOf(ch));
        }
        if((ch>='a'&&ch<='f')||(ch>='A'&&ch<='F')){
            switch(ch){
                case 'a':
                case 'A':
                    //这里不用break是因为执行了return以后就不会在往下执行了
                    return 10;
                case 'b':
                case 'B':
                    return 11;
                case 'c':
                case 'C':
                    return 12;
                case 'd':
                case 'D':
                    return 13;
                case 'e':
                case 'E':
                    return 14;
                case 'f':
                case 'F':
                    return 15;
            }
        }
        //返回-1,代表出错
        return -1;
    }

    //十六进制的字符串形如:10,不包括前面的OX
    public static int hex2Int(String str){
        int result = 0;
        char[] hex = str.toCharArray();
        for(int i=0;i<hex.length;i++){
            if(getHexValue(hex[i])!=-1){
                result += getHexValue(hex[i])*Math.pow(16,hex.length-i-1);
            }else{
                return -1;
            }
        }
        return result;
    }
}

需要注意的几个方法

1.String.valueof(ch);

2.Integer.parseInt()

3.String.toCharArray()

4.Math.pow(a,b)

完~

posted @ 2021-10-20 18:08  ╰(‵□′)╯  阅读(280)  评论(0编辑  收藏  举报