在没有.parseInt()的情况下将十六进制转换为十进制;

时间:2014-04-28 20:21:35

标签: java

我正在编写一些代码,从十六进制转换为十进制,不使用内置的java函数,如Integer.parseInt(n,16);

这是我制作的,但它不起作用:

    public static int hexToDecimal(String hexInput) {
    String hexIn = hexInput.replace("", " ").trim();
    Scanner hex = new Scanner(hexIn);
    int decimal = 0;
    int power = 1;

    while (hex.hasNext() == true) {
        String temp = hex.next();

        if (temp.equals("1") == true) {
            decimal += 1 * power;
        } else if (temp.equals("2") == true) {
            decimal += 2 * power;
        } else if (temp.equals("3") == true) {
            decimal += 3 * power;
        } else if (temp.equals("4") == true) {
            decimal += 4 * power;
        } else if (temp.equals("5") == true) {
            decimal += 5 * power;
        } else if (temp.equals("6") == true) {
            decimal += 6 * power;
        } else if (temp.equals("7") == true) {
            decimal += 7 * power;
        } else if (temp.equals("8") == true) {
            decimal += 8 * power;
        } else if (temp.equals("9") == true) {
            decimal += 9 * power;
        } else if (temp.equals("A") == true) {
            decimal += 10 * power;
        } else if (temp.equals("B") == true) {
            decimal += 11 * power;
        } else if (temp.equals("C") == true) {
            decimal += 12 * power;
        } else if (temp.equals("D") == true) {
            decimal += 13 * power;
        } else if (temp.equals("E") == true) {
            decimal += 14 * power;
        } else if (temp.equals("F") == true) {
            decimal += 15 * power;
        }
        power = power * 16;
    }

    System.out.println(decimal);
    return decimal;
}

我可以帮忙吗?它似乎有一些基本的功能,但它打破了大多数输入。谢谢你的帮助!

2 个答案:

答案 0 :(得分:3)

当你向右扫描时,你会逐渐增加16的强大功率。这与你想要的完全相反。请尝试使用此逻辑,这比您现在所做的更简单:

public static int hexToDecimal(String hexInput) {
    int decimal = 0;
    int len = hexInput.length();

    for (int i = 0; i < len; ++i) {
        char c = hexInput.charAt(i);
        int cValue;

        switch (c) {
        case '1':
            cValue = 1;
            break;
        case '2':
            cValue = 2;
            break;
        . . .
        default: // unexpected character
            throw new IllegalArgumentException("Non-hex character " + c
                + " found at position " + i);
        }
        decimal = 16 * decimal + cValue;
    }
    return decimal;
}

它正如您现在所做的那样从左向右扫描,将已经处理的值乘以16,以便遇到每个新的十六进制数字。

答案 1 :(得分:1)

你必须反转输入字符串,因为按照你最方便的数字在右侧进行操作

hexInput=new StringBuilder(hexInput).reverse().toString();反向刺痛 或者只是以其他方式做电力,如

int power=Math.pow(16,hexInput.length()-1);

然后在循环结束时

power/=16;

我会使用第二种方法,因为你不必做额外的代码。