解析整数字符串(大于Integer.MAX_VALUE)

时间:2013-02-20 04:28:06

标签: java integer

假设我有这个字符串0xdadacafe(显然大于Integer.MAX_VALUE:0x7fffffff)。如果我使用Integer.parseInt(String, int)来解析它,我会得到NumberFormatException。有没有办法解析这个字符串并获得“无声”溢出?

换句话说,是否有任何方法可以解析此字符串并获取-623195394,这是您System.out.println(0xdadacafe);

时获得的值

(我可能不想做(int)Long.parseLong(String, int)

之类的事情

由于

2 个答案:

答案 0 :(得分:3)

您可以将其作为BigInteger读取,然后返回正确的int值。

BigInteger value = new BigInteger("dadacafe", 16); // 3671771902
value.intValue(); // -623195394

修改

re:评论说这很慢..

我的意思是,there's always this right

public static int parseInt(String s, int radix)
    throws NumberFormatException
{
    if (s == null) {
      throw new NumberFormatException("null");
    }

    if (radix < Character.MIN_RADIX) {
      throw new NumberFormatException("radix " + radix +
          " less than Character.MIN_RADIX");
    }

    if (radix > Character.MAX_RADIX) {
      throw new NumberFormatException("radix " + radix +
          " greater than Character.MAX_RADIX");
    }

    int result = 0;
    boolean negative = false;
    int i = 0, len = s.length();
    int digit;

    if (len > 0) {
      char firstChar = s.charAt(0);
      if (firstChar < '0') { // Possible leading "-"
        if (firstChar == '-') {
          negative = true;
        } else
          throw new NumberFormatException(s);

        if (len == 1) // Cannot have lone "-"
          throw new NumberFormatException(s);
        i++;
      }
      while (i < len) {
        // Accumulating negatively avoids surprises near MAX_VALUE
        digit = Character.digit(s.charAt(i++),radix);
        if (digit < 0) {
          throw new NumberFormatException(s);
        }
        result *= radix;
        result -= digit;
      }
    } else {
      throw new NumberFormatException(s);
    }
    return negative ? result : -result;
}

但是在这一点上,我会开始认为这可能不是正确解决问题。我不确定你是否会反对现有的软件,或者情况如何,但如果“快速轻微”的溢出实际上是你真正需要的东西 - 它可能不会比这更好

答案 1 :(得分:3)

int i = (int)Long.parseLong("0xdadacafe".substring(2), 16);