问题:
计算机系统中经常会用到十六进制,那么如何将十六进制转换为十六进制呢?
例如:
十进制123转换为十六进制数为7B,1234转换为十六进制为4D2。
代码实现:
public class Dec2Hex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个十进制数:");
int decimal = input.nextInt();
String hex = "";
while (decimal!=0){
int hexValue = decimal%16;
char hexDigit = ( 0 <= hexValue && hexValue <=9)?(char)(hexValue+'0') : (char) (hexValue - 10 + 'A');
hex =hexDigit+hex ;
decimal=decimal/16;
}
System.out.println("转换后的十六进制为:" + hex);
}
}
运行结果:
请输入一个十进制数:
1234
转换后的十六进制为:4D2