Java如何将十六进制数转换为十进制数的自编程序

package com.swift;//所属包

import java.util.Scanner;//导入扫描器

public class Hex2Decimal {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("please enter a Hex:");
        String hex = scan.nextLine();//读取一行
        hex = hex.toUpperCase();//转换成大写字母
        System.out.println("The hex is:" + hex);//输出一下
        int decimal = 0;
        for (int i = 0; i < hex.length(); i++) {
            if (hexChar2Decimal(hex.charAt(hex.length() - 1 - i)) != -1) {//从16进制数的最后一个字符开始获取
                decimal = (int) (decimal + hexChar2Decimal(hex.charAt(hex.length() - 1 - i)) * Math.pow(16, i));//乘以16的0次幂,然后++
            } else {
                System.out.println("enter error, decimal will be zero!");//如果等于-1则是非法字符
                break;
            }
        }
        System.out.println("decimal=" + decimal);
    }

    private static int hexChar2Decimal(char charAt) {
        if (charAt >= 'A' && charAt <= 'F')
            return charAt - 'A' + 10;//A~F转换成10进制数
        else if (charAt >= '0' && charAt <= '9')
            return charAt-'0';//0~9字符转换成10进制
        else
            return -1;
    }

}

十六进制数AF3转换原理:3*16^0+F*16^1+A*16^2  其中^表示幂运算,F和A需转换成十进制数15和10