NumberFormatException到许多十六进制字符

时间:2013-09-01 03:09:13

标签: java android

当我将许多十六进制字符插入到正在转换为整数值的字符串中时,我收到异常。

代码:

//variables used in this problem
int INT_MAX = 2147483647;
int INT_MIN = -2147483648;
int currentBase = 16;
string displayValue;

switch(currentBase) {
    case 16:
        if((Integer.valueOf(displayValue + "F", currentBase) >= INT_MIN) && (Integer.valueOf(displayValue + "F", currentBase) <= INT_MAX))
        {
            displayValue += "F";
        }
        break;
}

错误消息:

E/AndroidRuntime(6944): Caused by: java.lang.NumberFormatException: Invalid int: "FFFFFFFF"
E/AndroidRuntime(6944):     at java.lang.Integer.invalidInt(Integer.java:138)
E/AndroidRuntime(6944):     at java.lang.Integer.parse(Integer.java:378)
E/AndroidRuntime(6944):     at java.lang.Integer.parseInt(Integer.java:366)
E/AndroidRuntime(6944):     at java.lang.Integer.valueOf(Integer.java:510)
E/AndroidRuntime(6944):     at com.example.calculator.MainActivity.send_f(MainActivity.java:968)

我需要这个字符串的值不大于int(32位)。有什么建议吗?

4 个答案:

答案 0 :(得分:1)

Greg Hewgill的评论是正确的。看起来你正试图自动解释这些位。可能最简单的事情就是

 Long.valueOf(displayValue + "F", currentBase).intValue();

获取位,然后将它们截断为int。当然,现在你有责任确保Long.valueOf的参数符合32位。

答案 1 :(得分:1)

FFFFFFFF太大,max int值为0x7FFFFFFF,解决方法是

int i = (int)Long.parseLong(hexStr, 16);

答案 2 :(得分:0)

try {
    // try your calculation here
} catch (NumberFormatException e) {
    // assign the variable the max/min value instead
    // or whatever behavior you want
}

此代码将为超出范围的数字提供默认行为。

答案 3 :(得分:0)

在我看来,你正在使用一个错误的方法进行十六进制字符串到int转换,如果我的理解错误让我知道

我引用了一个重复的帖子

    String hex = "ff"

// small values
    int value = Integer.parseInt(hex, 16);  

// big values
    BigInteger value = new BigInteger(hex, 16);

refer for the duplicate post i quoted

API refrence for the method