The java program converts a decimal number into a hexadecimal number

Analysis
 In order to convert decimal to hexadecimal number, the program uses a loop to divide the decimal number by 16 and get the rest. The remainder is converted to a string in hexadecimal form. Next, this character is appended to the end of the string representing the hexadecimal number. This string representing a hexadecimal number is initially empty. Divide this decimal number by 16 to remove a hexadecimal number from the number. Repeat these operations in a loop until the quotient is 0.
 The program converts a hexadecimal number between 0 to 15 into a hexadecimal character. If hexValue is between 0 and 9, then it is converted to (char) (hexValue + '0')
. When adding a character to an integer, the Unicode code of the character is used in the calculation. For example: If hexValue is 5, then (char) (hexValue + '0') returns 5. Similarly, if hexValue is between 10 and 15, then it will be converted to (char)(hexValue-10+'A')
. For example, if hexValue is 11, then (char )(hexValue-10+' A') returns B.

Code:

import java.util.Scanner;

public class DecToHex {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a decimal number:");
        int decimal = input.nextInt();

        String hex = "";//十六进制数的字符串初始时为空
        while (decimal != 0) {
    
    
            int hexValue = decimal % 16;
            //把一个十进制值转化为十六进制值
            char hexDigit = (hexValue <= 9 && hexValue >= 0) ?
                    (char) (hexValue + '0') : (char) (hexValue - 10 + 'A');
            hex=hexDigit+hex;
            decimal=decimal/16;
        }
        System.out.println("The hex number is "+hex);
    }
}

Guess you like

Origin blog.csdn.net/Light20000309/article/details/104663752