将十进制数转换为十六进制数,用java实现
作者:互联网
代码:
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);
}
}
结果显示:
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
程序提示用户输入一个十进制数字,将其转换为一个十六进制形式的字符串,然后显示结果。为了将十进制转换为十六进制数,程序运用循环不断地将十进制数除以16,得到其余数。余数转换为一个十六进制形式的字符串。接下来,这个字符被追加在表示十六进制数的字符串的后面。这个表示十六进制数的字符串初始时为空。将这个十进制数除以16,就从该数中去掉一个十六进制数字。循环重复执行这些操作,直到商是0为止。
标签:十六进制,jdk1.8,java,lib,jar,jre,281,Java,十进制 来源: https://blog.csdn.net/weixin_42768634/article/details/113604922