设为首页 加入收藏

TOP

Java如何将十六进制数转换为十进制数的程序
2017-10-11 15:20:02 】 浏览:423
Tags: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) {
                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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Set 里的元素是不能重复的,那么.. 下一篇什么是内部类? Static Nested Cl..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目