您的位置:首页 > 编程语言 > Java开发

16进制转10进制使用霍纳算法(java版)

2017-09-26 22:56 405 查看
import java.util.Scanner;
public class Hex2Dec
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

System.out.println("Enter a hex number");
String hex = input.nextLine();

System.out.println("The decimal value for hex number"+ hex + "is " + hexToDecimal(hex.toUpperCase()));//全部转换成了大写字母
}

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);
/**使用了霍纳算法
* 原来正常算法A B 8 C= 10*16^3+11*16^2+8*16+12
* 改进后:
* ( (10*16+11)*16+8 )*16+12
*/

}
return decimalValue;
}

public static int hexCharToDecimal(char ch)
{
if(ch >= 'A' && ch <= 'Z')//字母
return 10+ ch - 'A';
else //数字
return ch - '0';
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java