一.介绍
程序从控制台读取一个字符串,然后调用hexToDecimal方法,将一个十六进制字符串转换为十进制.字符可以大写也可以小写。在调用hexToDecimal方法之前将它们都转换成大写。
定义的hexToDecimal方法返回一个整形值。这个字符串的长度是由调用的hex.length()方法确定的。
定义的hexCharToDecimal返回一个十六进制字符的十进制数值。
三.代码
package com.zhuo.base.com.zhuo.base;
import java.util.Locale;
import java.util.Scanner;
public class Hex2Dec {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a hex number: ");//提示用户输入字符串
String hex = input.nextLine();
System.out.println("The decimal value for has number " + hex + " is " + hexToDecimal(hex.toUpperCase(Locale.ROOT)));
}
public static int hexToDecimal(String hex) {
int decimalValue = 0;
for (int i = 0;i < hex.length();i++) {
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
}
return decimalValue;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F')
return ch - 'A' + 10;
else
return ch - '0';
}
}
三.结果显示
Enter a hex number: AB8C
The decimal value for has number AB8C is 43916
Process finished with exit code 0