Convert a decimal number to a hexadecimal number, implemented in java

1. Introduction

The program prompts the user to enter a decimal number, converts it to a string in hexadecimal form, and then displays the result. In order to convert decimal to hexadecimal number, the program uses a loop to continuously divide the decimal number by 16 to get the rest. The remainder is converted to a string in hexadecimal form. Next, this character is appended to the string representing the hexadecimal number. This string representing a hexadecimal number is initially empty. Dividing this decimal number by 16, removes a hexadecimal number from the number. Repeat these operations in a loop until the quotient is zero.

2. Code

package com.zhuo.base.com.zhuo.base;

import java.util.Scanner;

public class DexHex {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        //提示用户输入十进制数字
        System.out.print("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 /= 16;
        }
        System.out.println("The hex number is " + hex);
    }
}

Three. Results display

D:\Java\jdk1.8.0_281\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=54847:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\Java\jdk1.8.0_281\jre\lib\charsets.jar;D:\Java\jdk1.8.0_281\jre\lib\deploy.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\access-bridge-64.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\cldrdata.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\dnsns.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\jaccess.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\jfxrt.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\localedata.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\nashorn.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\sunec.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\sunpkcs11.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\zipfs.jar;D:\Java\jdk1.8.0_281\jre\lib\javaws.jar;D:\Java\jdk1.8.0_281\jre\lib\jce.jar;D:\Java\jdk1.8.0_281\jre\lib\jfr.jar;D:\Java\jdk1.8.0_281\jre\lib\jfxswt.jar;D:\Java\jdk1.8.0_281\jre\lib\jsse.jar;D:\Java\jdk1.8.0_281\jre\lib\management-agent.jar;D:\Java\jdk1.8.0_281\jre\lib\plugin.jar;D:\Java\jdk1.8.0_281\jre\lib\resources.jar;D:\Java\jdk1.8.0_281\jre\lib\rt.jar;D:\IdeaProjects\JavaSE\out\production\Practise com.zhuo.base.com.zhuo.base.DexHex
Enter a decimal number: 1234
The hex number is 4D2

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113604922