首页 > 代码库 > 将十进制数转换为十六进制数

将十进制数转换为十六进制数

package welcome;

import java.util.Scanner;

public class Decimal2HexCoversion {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter an decimal number: ");
        int decimal = in.nextInt();
        
        // 调用十进制数转十六进制的方法
        System.out.println("The hex number for decimal " + decimal + " is " + decimalToHex(decimal));
    }
    
    public static String decimalToHex(int decimal){
        String hex = "";
        
        while(decimal != 0){
            int hexValue = http://www.mamicode.com/decimal % 16;
            hex = toHexChar(hexValue) + hex;
            decimal = decimal / 16;
        }
        return hex;
    }
    
    public static char toHexChar(int hexValue){
        if(hexValue <= 9 && hexValue >= 0){
            return (char)(hexValue + ‘0‘);
        }else{
            return (char)(hexValue - 10 + ‘A‘);
        }
    }
    
    
}

 

技术分享

 

将十进制数转换为十六进制数