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');
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM