Java实现十六进制和十进制代码互相转

十六进制转换为十进制代码


import java.util.*;

public class Transfer {
public static  void main(String[]args){
Scanner input=new Scanner(System.in);

String hex=input.nextLine();
System.out.println("hex:"+hex.toUpperCase());
System.out.println("Decimal:"+hexToDecimal(hex.toUpperCase()));
// char c='0';
// System.out.println(hexCharToDecimal(c));
}

public static int hexToDecimal(String hex)
{
int decimalValue=0;
for(int i=0;i<hex.length();i++)
{
char hexChar=hex.charAt(i);
decimalValue=decimalValue*16+hexCharToDecimal(hexChar);
}
return decimalValue;
}

public static int hexCharToDecimal(char hexChar)
{
if(hexChar>='A'&&hexChar<='F')
return 10+hexChar-'A';
else
return hexChar-'0';//切记不能写成int类型的0,因为字符'0'转换为int时值为48
}

}


十进制数转十六进制数

/**
 * 
 */
package com.succez.task2;

import java.util.Scanner;

/**
 * <p>Copyright: Copyright (c) 2018</p>
 * <p>succez</p>
 * @author ZhangJinjin
 * @createdate 2018年5月4日
 */
public class intToHex_Alter {

    /**
     * 这次算法用了StringBuffer效率更好
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("请输入要转换的十进制的数:");
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();        
        System.out.println("转换的十六进制的数为:"+intToHex(n));
    }

    private static String intToHex(int n) {
        //StringBuffer s = new StringBuffer();
        StringBuilder sb = new StringBuilder(8);
        String a;
        char []b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        while(n != 0){
            sb = sb.append(b[n%16]);
            n = n/16;            
        }
        a = sb.reverse().toString();
        return a;
    }

}
复制代码


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页