package lsh.element.numbersystem;
import java.util.Scanner;
/**
*
* @desc 有意思的地方:两种思想得到的结果都是正确的,但是超出int类型最大之后,错误值却不同
*
* @author
* LSH
* 2018年9月23日
*/
public class HexToDecimalConversion {
public static void main(String[] args) {
System.out.println((int)'0');
Scanner input = new Scanner(System.in);
System.out.print("请输入一个十六进制的数:");
String hex = input.nextLine();
System.out.println("【添位思想】你输入的十六进制数对应的数值是: "+hex+" = "+hexToDecimal_addBit(hex.toUpperCase()));
System.out.println("【结果导向】你输入的十六进制数对应的数值是: "+hex+" = "+hexToDecimal_resultOriented(hex.toUpperCase()));
input.close();
}
/**
* 思想:结果为导向,从左到右,先高位后低位
* @param hex
* @return
*/
public static int hexToDecimal_resultOriented(String hex) {
int decimalValue = 0;
//先计算高位,再计算低位
// for (int i = 0; i < hex.length(); i++) {
// char c = hex.charAt(i);
// decimalValue += (int) ((hexCharToDecimal(c))*Math.pow(16, hex.length()-1-i));
// }
//先计算低位,再计算高位
for (int i = hex.length()-1, j = 0; i >= 0; i--,j++) {
char c = hex.charAt(i);
decimalValue += (int) ((hexCharToDecimal(c))*Math.pow(16, j));
}
return decimalValue;
}
/**
* 思想:添位思想,在原来数值的基础上每在后面添一位,原来的数值要乘以16
* 添位思想,颇有蚕食进阶的味道,步步累进,更为高明
* @param hex
* @return
*/
public static int hexToDecimal_addBit(String hex) {
int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
char c = hex.charAt(i);
decimalValue = decimalValue*16 + hexCharToDecimal(c);
}
return decimalValue;
}
public static int hexCharToDecimal(char c) {
if(c>='A' && c<='F') {
return 10+c-'A';
}
return c-'0';
}
}