Java中的十六进制到十进制

时间:2015-10-25 13:54:00

标签: java hex decimal

我的错误在哪里?

  

结果通常是48到高。对于0的情况,我将添加一个If语句。如果有可能的话,我想留下两个循环:)

public static int HexadecimalToDecimal(String hex1) {

        char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

        int intCache = 0;
        int runner = 0;
        int help = 0;
        int number = 0;

        for (int i = hex1.length(); i > 0; i--) {


            while (hex1.charAt(i - 1) != hex[help]) {
                help++;
                number = hex[help];
            }
            intCache += number * (Math.pow(16, runner));
            runner++;
        }

        return intCache;

    }

1 个答案:

答案 0 :(得分:2)

运行时

public static void main(String[] args) {
    // Prime numbers in a range
    int range = 15;
    int num = 1;
    int count = 0;
    boolean prime = true;
    while (count < range) {
        num = num + 1;
        prime = true;
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                prime = false;
                break;
            }
        }
        if (prime) {
            count++;
            System.out.println(num);
        }
    }
}

为数字指定字符值( number = hex[help]; ),而不是数字值0.“0”的字符值为48。