Java 实例 十进制到十六进制的转换

来源:这里教程网 时间:2026-02-17 20:17:13 作者:

将十进制数转换为十六进制数有以下两种方法:

1)使用Integer类的toHexString()方法。

2)通过编写自己的逻辑进行转换,而无需使用任何预定义的方法。

方法 1:使用toHexString()方法的十进制到十六进制转换

import java.util.Scanner;class DecimalToHexExample{    public static void main(String args[])    {      Scanner input = new Scanner( System.in );      System.out.print("Enter a decimal number : ");      int num =input.nextInt();      // calling method toHexString()      String str = Integer.toHexString(num);      System.out.println("Method 1: Decimal to hexadecimal: "+str);    }}

输出:

Enter a decimal number : 123Method 1: Decimal to hexadecimal: 7b

方法 2:不使用预定义的方法的十进制到十六进制转换

import java.util.Scanner;class DecimalToHexExample{   public static void main(String args[])   {     Scanner input = new Scanner( System.in );     System.out.print("Enter a decimal number : ");     int num =input.nextInt();     // For storing remainder     int rem;     // For storing result     String str2="";      // Digits in hexadecimal number system     char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};     while(num>0)     {       rem=num%16;        str2=hex[rem]+str2;        num=num/16;     }     System.out.println("Method 2: Decimal to hexadecimal: "+str2);  }}

输出:

Enter a decimal number : 123Method 2: Decimal to hexadecimal: 7B

相关推荐