- public class HexToDecimal {
- public static void main(String[] args) {
- System.out.println((char) hexToDecimal("4e2d"));//中
- }
- private static int hexToDecimal(String hex) {
- char ch;
- int len = hex.length();
- int value = 0;
- for (int x = 0; x < len;) {
- ch = hex.charAt(x++);
- switch (ch) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- value = (value << 4) + ch - '0';
- break;
- case 'a':
- case 'b':
- case 'c':
- case 'd':
- case 'e':
- case 'f':
- value = (value << 4) + 10 + ch - 'a';
- break;
- case 'A':
- case 'B':
- case 'C':
- case 'D':
- case 'E':
- case 'F':
- value = (value << 4) + 10 + ch - 'A';
- break;
- default:
- throw new IllegalArgumentException(ch + "'snt hex char.");
- }
- }
- return value;
- }
- }
当然在平时使用时,我们一般使用Integer.parseInt方法来转换即可,这里只是另一种实现罢了。