Java中将10进制转换成16进制

import java.util.Scanner;
public class Decimal2HexConversion {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print("输入一个十进制数: ");
        int decimal = input.nextInt();
        System.out.println("十进制数 " + decimal +"的十六进制数为: " + decimalToHex(decimal));
        if(!input.hasNext())
            input.close();
    }
   
    public static String decimalToHex(int decimal) {
        String hex = "";
        while(decimal != 0) {
            int hexValue = decimal % 16;
            hex = toHexChar(hexValue) + hex;
            decimal = decimal / 16;
        }
        return  hex;
    }
    //将0~15的十进制数转换成0~F的十六进制数
    public static char toHexChar(int hexValue) {
        if(hexValue <= 9 && hexValue >= 0)
            return (char)(hexValue + '0');
        else
            return (char)(hexValue - 10 + 'A');
    }
}

posted @ 2016-05-23 12:00  撸码之路  阅读(14930)  评论(0编辑  收藏  举报