码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-10-06 15:56:44      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:bre   程序   ++   next   math   error   hex   enter   ati   

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) {
                decimal = (int) (decimal + hexChar2Decimal(hex.charAt(hex.length() - 1 - i)) * Math.pow(16, i));
            } else {
                System.out.println("enter error, decimal will be zero!");
                break;
            }
        }
        System.out.println("decimal=" + decimal);
    }

    private static int hexChar2Decimal(char charAt) {
        if (charAt >= ‘A‘ && charAt <= ‘F‘)
            return charAt - ‘A‘ + 10;
        else if (charAt >= ‘0‘ && charAt <= ‘9‘)
            return charAt-‘0‘;
        else
            return -1;
    }

}

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

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

标签:bre   程序   ++   next   math   error   hex   enter   ati   

原文地址:http://www.cnblogs.com/qingyundian/p/7631605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!