分析
为了将十进制转换为十六进制数,程序运用循环不断地将十进制数除以16 , 得到其余数。 余数转换为一个十六进制形式的字符串 。接下来 ,这个字符被追加在表示十六进制数的字符串的后面 。这个表示十六进制数的字符串初始时为空。 将这个十进制数除以 16 , 就从该数中去掉一个十六进制数字 。 循环重复执行这些操作,直到商是 0 为止 。
程序将 0 到 15 之间的十六进制数转换为一个十六进制字符 。如果hexValue 在 0 到 9之间 , 那它就被转换为 (char) (hexValue + ‘0’)
。当一个字符和一个整数相加时 , 计算时使用的是字符的 Unicode 码 。 例如 : 如果 hexValue 为 5 , 那么 (char) (hexValue + ‘0’)返回 5 。 类 似 地 , 如 果 hexValue 在 1 0 到 15之 间, 那 么 它 就 被 转 换 为(char)( hexValue-10+‘A’)
。 例如,如果 hexValue 是 11, 那么 ( char )(hexValue-10+’ A ') 返回 B 。
代码实现:
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);
}
}