2

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

换句话说,有没有办法解析这个字符串并 get -623195394,如果你这样做,这是你得到的值System.out.println(0xdadacafe);

(而且我可能不想做类似的事情(int)Long.parseLong(String, int)

谢谢

4

2 回答 2

4

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

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

编辑:

回复:评论说这很慢..

我的意思是,总是有这样的权利

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;
}

但是在这一点上,我会开始认为这可能没有正确解决问题。我不确定你是否在反对现有的软件,或者情况可能是什么,但如果'fast-as-light' int 溢出实际上是你真正需要的东西 - 它可能不会比这更好.

于 2013-02-20T04:48:05.513 回答
3

尝试

int i = (int)Long.parseLong("0xdadacafe".substring(2), 16);
于 2013-02-20T04:49:12.893 回答