Java 实例 十进制到十六进制的转换 | 您所在的位置:网站首页 › 1001b转换为十六进制数为 › Java 实例 十进制到十六进制的转换 |
将十进制数转换为十六进制数有以下两种方法: 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 : 123 Method 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 : 123 Method 2: Decimal to hexadecimal: 7B |
CopyRight 2018-2019 实验室设备网 版权所有 |