Java Code Examples for java.math.BigInteger#negate()

The following examples show how to use java.math.BigInteger#negate() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jdk8u_jdk   File: ModPow.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    Random rnd = new Random(1234);

    for (int i=0; i<2000; i++) {
        BigInteger m = new BigInteger(800, rnd);
        BigInteger base = new BigInteger(16, rnd);
        if (rnd.nextInt() % 1 == 0)
            base = base.negate();
        BigInteger exp = new BigInteger(8, rnd);

        BigInteger z = base.modPow(exp, m);
        BigInteger w = base.pow(exp.intValue()).mod(m);
        if (!z.equals(w)){
            System.err.println(base +" ** " + exp + " mod "+ m);
            System.err.println("modPow : " + z);
            System.err.println("pow.mod: " + w);
            throw new RuntimeException("BigInteger modPow failure.");
        }
    }
}
 
Example 2
/**
 * Formats a {@link BigFraction} object to produce a string.  The BigFraction
 * is output in proper format.
 *
 * @param fraction the object to format.
 * @param toAppendTo where the text is to be appended
 * @param pos On input: an alignment field, if desired. On output: the
 *            offsets of the alignment field
 * @return the value passed in as toAppendTo.
 */
@Override
public StringBuffer format(final BigFraction fraction,
                           final StringBuffer toAppendTo, final FieldPosition pos) {
    
    pos.setBeginIndex(0);
    pos.setEndIndex(0);

    BigInteger num = fraction.getNumerator();
    BigInteger den = fraction.getDenominator();
    BigInteger whole = num.divide(den);
    num = num.remainder(den);
    
    if (!BigInteger.ZERO.equals(whole)) {
        getWholeFormat().format(whole, toAppendTo, pos);
        toAppendTo.append(' ');
        if (num.compareTo(BigInteger.ZERO) < 0) {
            num = num.negate();
        }
    }
    getNumeratorFormat().format(num, toAppendTo, pos);
    toAppendTo.append(" / ");
    getDenominatorFormat().format(den, toAppendTo, pos);
    
    return toAppendTo;
}
 
Example 3
Source Project: coming   File: Lang_3_NumberUtils_t.java    License: MIT License 6 votes vote down vote up
/**
 * <p>Convert a <code>String</code> to a <code>BigInteger</code>;
 * since 3.2 it handles hex (0x or #) and octal (0) notations.</p>
 *
 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
 * 
 * @param str  a <code>String</code> to convert, may be null
 * @return converted <code>BigInteger</code> (or null if the input is null)
 * @throws NumberFormatException if the value cannot be converted
 */
public static BigInteger createBigInteger(final String str) {
    if (str == null) {
        return null;
    }
    int pos = 0; // offset within string
    int radix = 10;
    boolean negate = false; // need to negate later?
    if (str.startsWith("-")) {
        negate = true;
        pos = 1;
    }
    if (str.startsWith("0x", pos) || str.startsWith("0x", pos)) { // hex
        radix = 16;
        pos += 2;
    } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer)
        radix = 16;
        pos ++;
    } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits
        radix = 8;
        pos ++;
    } // default is to treat as decimal

    final BigInteger value = new BigInteger(str.substring(pos), radix);
    return negate ? value.negate() : value;
}
 
Example 4
Source Project: Arend   File: CheckTypeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public @Nullable TypecheckingResult checkNumber(@NotNull BigInteger number, @Nullable CoreExpression expectedType, @NotNull ConcreteExpression marker) {
  if (!((expectedType == null || expectedType instanceof Expression) && marker instanceof Concrete.Expression)) {
    throw new IllegalArgumentException();
  }

  boolean isNegative = number.signum() < 0;
  Expression resultExpr;
  try {
    int value = number.intValueExact();
    resultExpr = new SmallIntegerExpression(isNegative ? -value : value);
  } catch (ArithmeticException e) {
    resultExpr = new BigIntegerExpression(isNegative ? number.negate() : number);
  }

  TypecheckingResult result;
  if (isNegative) {
    result = new TypecheckingResult(ExpressionFactory.Neg(resultExpr), ExpressionFactory.Int());
  } else {
    result = new TypecheckingResult(resultExpr, ExpressionFactory.Nat());
  }
  return checkResult((Expression) expectedType, result, (Concrete.Expression) marker);
}
 
Example 5
/**
 * Decode a {@link java.math.BigInteger} from the supplied {@link String} value.
 * <p>Supports decimal, hex, and octal notation.
 * @see BigInteger#BigInteger(String, int)
 */
private static BigInteger decodeBigInteger(String value) {
	int radix = 10;
	int index = 0;
	boolean negative = false;

	// Handle minus sign, if present.
	if (value.startsWith("-")) {
		negative = true;
		index++;
	}

	// Handle radix specifier, if present.
	if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
		index += 2;
		radix = 16;
	}
	else if (value.startsWith("#", index)) {
		index++;
		radix = 16;
	}
	else if (value.startsWith("0", index) && value.length() > 1 + index) {
		index++;
		radix = 8;
	}

	BigInteger result = new BigInteger(value.substring(index), radix);
	return (negative ? result.negate() : result);
}
 
Example 6
Source Project: Java8CN   File: DecimalFormat.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Format a BigInteger to produce a string.
 * @param number    The BigInteger to format
 * @param result    where the text is to be appended
 * @param delegate notified of locations of sub fields
 * @return The formatted number string
 * @exception        ArithmeticException if rounding is needed with rounding
 *                   mode being set to RoundingMode.UNNECESSARY
 * @see java.text.FieldPosition
 */
private StringBuffer format(BigInteger number, StringBuffer result,
                           FieldDelegate delegate, boolean formatLong) {
    if (multiplier != 1) {
        number = number.multiply(getBigIntegerMultiplier());
    }
    boolean isNegative = number.signum() == -1;
    if (isNegative) {
        number = number.negate();
    }

    synchronized(digitList) {
        int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits;
        if (formatLong) {
            maxIntDigits = super.getMaximumIntegerDigits();
            minIntDigits = super.getMinimumIntegerDigits();
            maxFraDigits = super.getMaximumFractionDigits();
            minFraDigits = super.getMinimumFractionDigits();
            maximumDigits = maxIntDigits + maxFraDigits;
        } else {
            maxIntDigits = getMaximumIntegerDigits();
            minIntDigits = getMinimumIntegerDigits();
            maxFraDigits = getMaximumFractionDigits();
            minFraDigits = getMinimumFractionDigits();
            maximumDigits = maxIntDigits + maxFraDigits;
            if (maximumDigits < 0) {
                maximumDigits = Integer.MAX_VALUE;
            }
        }

        digitList.set(isNegative, number,
                      useExponentialNotation ? maximumDigits : 0);

        return subformat(result, delegate, isNegative, true,
            maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
    }
}
 
Example 7
Source Project: astor   File: BigFraction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a {@link BigFraction} given the numerator and denominator as
 * {@code BigInteger}. The {@link BigFraction} is reduced to lowest terms.
 *
 * @param num the numerator, must not be {@code null}.
 * @param den the denominator, must not be {@code null}.
 * @throws ZeroException if the denominator is zero.
 * @throws NullArgumentException if either of the arguments is null
 */
public BigFraction(BigInteger num, BigInteger den) {
    MathUtils.checkNotNull(num, LocalizedFormats.NUMERATOR);
    MathUtils.checkNotNull(den, LocalizedFormats.DENOMINATOR);
    if (BigInteger.ZERO.equals(den)) {
        throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR);
    }
    if (BigInteger.ZERO.equals(num)) {
        numerator   = BigInteger.ZERO;
        denominator = BigInteger.ONE;
    } else {

        // reduce numerator and denominator by greatest common denominator
        final BigInteger gcd = num.gcd(den);
        if (BigInteger.ONE.compareTo(gcd) < 0) {
            num = num.divide(gcd);
            den = den.divide(gcd);
        }

        // move sign to numerator
        if (BigInteger.ZERO.compareTo(den) > 0) {
            num = num.negate();
            den = den.negate();
        }

        // store the values in the final fields
        numerator   = num;
        denominator = den;

    }
}
 
Example 8
Source Project: astor   File: BigFraction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * Create a {@link BigFraction} given the numerator and denominator as
 * <code>BigInteger</code>. The {@link BigFraction} is reduced to lowest terms.
 * </p>
 *
 * @param num
 *            the numerator, must not be <code>null</code>.
 * @param den
 *            the denominator, must not be <code>null</code>.
 * @throws ArithmeticException
 *             if the denominator is <code>zero</code>.
 * @throws NullPointerException
 *             if the numerator or the denominator is <code>zero</code>.
 */
public BigFraction(BigInteger num, BigInteger den) {
    if (num == null) {
        throw MathRuntimeException.createNullPointerException("numerator is null");
    }
    if (den == null) {
        throw MathRuntimeException.createNullPointerException("denominator is null");
    }
    if (BigInteger.ZERO.equals(den)) {
        throw MathRuntimeException.createArithmeticException(FORBIDDEN_ZERO_DENOMINATOR);
    }
    if (BigInteger.ZERO.equals(num)) {
        numerator   = BigInteger.ZERO;
        denominator = BigInteger.ONE;
    } else {

        // reduce numerator and denominator by greatest common denominator
        final BigInteger gcd = num.gcd(den);
        if (BigInteger.ONE.compareTo(gcd) < 0) {
            num = num.divide(gcd);
            den = den.divide(gcd);
        }

        // move sign to numerator
        if (BigInteger.ZERO.compareTo(den) > 0) {
            num = num.negate();
            den = den.negate();
        }

        // store the values in the final fields
        numerator   = num;
        denominator = den;

    }
}
 
Example 9
/**
 * Sanity test for Burnikel-Ziegler division.  The Burnikel-Ziegler division
 * algorithm is used when each of the dividend and the divisor has at least
 * a specified number of ints in its representation.  This test is based on
 * the observation that if {@code w = u*pow(2,a)} and {@code z = v*pow(2,b)}
 * where {@code abs(u) > abs(v)} and {@code a > b && b > 0}, then if
 * {@code w/z = q1*z + r1} and {@code u/v = q2*v + r2}, then
 * {@code q1 = q2*pow(2,a-b)} and {@code r1 = r2*pow(2,b)}.  The test
 * ensures that {@code v} is just under the B-Z threshold, that {@code z} is
 * over the threshold and {@code w} is much larger than {@code z}. This
 * implies that {@code u/v} uses the standard division algorithm and
 * {@code w/z} uses the B-Z algorithm.  The results of the two algorithms
 * are then compared using the observation described in the foregoing and
 * if they are not equal a failure is logged.
 */
public static void divideLarge() {
    int failCount = 0;

    BigInteger base = BigInteger.ONE.shiftLeft(BITS_BURNIKEL_ZIEGLER + BITS_BURNIKEL_ZIEGLER_OFFSET - 33);
    for (int i=0; i<SIZE; i++) {
        BigInteger addend = new BigInteger(BITS_BURNIKEL_ZIEGLER + BITS_BURNIKEL_ZIEGLER_OFFSET - 34, rnd);
        BigInteger v = base.add(addend);

        BigInteger u = v.multiply(BigInteger.valueOf(2 + rnd.nextInt(Short.MAX_VALUE - 1)));

        if(rnd.nextBoolean()) {
            u = u.negate();
        }
        if(rnd.nextBoolean()) {
            v = v.negate();
        }

        int a = BITS_BURNIKEL_ZIEGLER_OFFSET + rnd.nextInt(16);
        int b = 1 + rnd.nextInt(16);
        BigInteger w = u.multiply(BigInteger.ONE.shiftLeft(a));
        BigInteger z = v.multiply(BigInteger.ONE.shiftLeft(b));

        BigInteger[] divideResult = u.divideAndRemainder(v);
        divideResult[0] = divideResult[0].multiply(BigInteger.ONE.shiftLeft(a - b));
        divideResult[1] = divideResult[1].multiply(BigInteger.ONE.shiftLeft(b));
        BigInteger[] bzResult = w.divideAndRemainder(z);

        if (divideResult[0].compareTo(bzResult[0]) != 0 ||
                divideResult[1].compareTo(bzResult[1]) != 0) {
            failCount++;
        }
    }

    report("divideLarge", failCount);
}
 
Example 10
Source Project: coming   File: Math_36_BigFraction_s.java    License: MIT License 5 votes vote down vote up
/**
 * Create a {@link BigFraction} given the numerator and denominator as
 * {@code BigInteger}. The {@link BigFraction} is reduced to lowest terms.
 *
 * @param num the numerator, must not be {@code null}.
 * @param den the denominator, must not be {@code null}.
 * @throws ZeroException if the denominator is zero.
 * @throws NullArgumentException if either of the arguments is null
 */
public BigFraction(BigInteger num, BigInteger den) {
    MathUtils.checkNotNull(num, LocalizedFormats.NUMERATOR);
    MathUtils.checkNotNull(den, LocalizedFormats.DENOMINATOR);
    if (BigInteger.ZERO.equals(den)) {
        throw new ZeroException(LocalizedFormats.ZERO_DENOMINATOR);
    }
    if (BigInteger.ZERO.equals(num)) {
        numerator   = BigInteger.ZERO;
        denominator = BigInteger.ONE;
    } else {

        // reduce numerator and denominator by greatest common denominator
        final BigInteger gcd = num.gcd(den);
        if (BigInteger.ONE.compareTo(gcd) < 0) {
            num = num.divide(gcd);
            den = den.divide(gcd);
        }

        // move sign to numerator
        if (BigInteger.ZERO.compareTo(den) > 0) {
            num = num.negate();
            den = den.negate();
        }

        // store the values in the final fields
        numerator   = num;
        denominator = den;

    }
}
 
Example 11
Source Project: protect   File: BNPoint.java    License: MIT License 5 votes vote down vote up
/**
 * Compute ks*this + kr*Y. This is useful in the verification part of several
 * signature algorithms, and (hopely) faster than two scalar multiplications.
 *
 * @param ks scalar by which this point is to be multiplied.
 * @param kr scalar by which Y is to be multiplied.
 * @param Y  a curve point.
 *
 * @return ks*this + kr*Y
 */
public BNPoint simultaneous(BigInteger ks, BigInteger kr, BNPoint Y) {
	assert (isOnSameCurve(Y));
	BNPoint R = null;
	if (pp16P == null) {
		BNPoint[] hV = new BNPoint[16];
		BNPoint P = this.normalize();
		Y = Y.normalize();
		if (ks.signum() < 0) {
			ks = ks.negate();
			P = P.negate();
		}
		if (kr.signum() < 0) {
			kr = kr.negate();
			Y = Y.negate();
		}
		hV[0] = E.infinity;
		hV[1] = P;
		hV[2] = Y;
		hV[3] = P.add(Y);
		for (int i = 4; i < 16; i += 4) {
			hV[i] = hV[i >> 2].twice(1);
			hV[i + 1] = hV[i].add(hV[1]);
			hV[i + 2] = hV[i].add(hV[2]);
			hV[i + 3] = hV[i].add(hV[3]);
		}
		int t = Math.max(kr.bitLength(), ks.bitLength());
		R = E.infinity;
		for (int i = (((t + 1) >> 1) << 1) - 1; i >= 0; i -= 2) {
			int j = (kr.testBit(i) ? 8 : 0) | (ks.testBit(i) ? 4 : 0) | (kr.testBit(i - 1) ? 2 : 0)
					| (ks.testBit(i - 1) ? 1 : 0);
			R = R.twice(2).add(hV[j]);
		}
	} else {
		R = this.multiply(ks).add(Y.multiply(ks));
	}
	return R;
}
 
Example 12
private void divideGaussian(BigInteger real, BigInteger imag, SortedMap<ComplexSym, Integer> complexMap) {
	real = real.abs();
	BigInteger temp;
	BigInteger norm = real.multiply(real).add(imag.multiply(imag));
	BigInteger realNum = ValA.multiply(real).add(ValB.multiply(imag));
	BigInteger imagNum = ValB.multiply(real).subtract(ValA.multiply(imag));
	if (realNum.mod(norm).signum() == 0 && imagNum.mod(norm).signum() == 0) {
		ValA = realNum.divide(norm);
		ValB = imagNum.divide(norm);
		if (real.signum() < 0) {
			real = real.negate();
			if (imag.signum() > 0) {
				temp = imag;
				imag = real;
				real = temp;
			} else {
				imag = imag.negate();
			}
		} else if (imag.signum() < 0) {
			imag = imag.negate();
			temp = imag;
			imag = real;
			real = temp;
		}
		ComplexSym c = ComplexSym.valueOf(F.ZZ(real), F.ZZ(imag));
		Integer value = complexMap.get(c);
		if (value == null) {
			complexMap.put(c, 1);
		} else {
			complexMap.put(c, value + 1);
		}
	}
}
 
Example 13
/**
 * Compute <code>value*signum</code> where value==null is treated as
 * value==0.
 * @param value Value to sanitize.
 * @param signum 0 to sanitize to 0, > 0 to sanitize to <code>value</code>, < 0 to sanitize to negative <code>value</code>.
 *
 * @return non-null {@link BigDecimal}.
 */
private static BigDecimal sanitize(BigInteger value, int signum) {
    if (signum == 0 || value == null) {
        return ZERO;
    }
    if (signum > 0) {
        return new BigDecimal(value);
    }
    return new BigDecimal(value.negate());
}
 
Example 14
Source Project: ghidra   File: OpBehaviorInt2Comp.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public BigInteger evaluateUnary(int sizeout, int sizein, BigInteger in1) {
	if (in1.signum() < 0) {
		throw new AssertException("Expected unsigned in value");
	}
	BigInteger res = in1.negate();
	return res;
}
 
Example 15
/**
 * Format a BigInteger to produce a string.
 * @param number    The BigInteger to format
 * @param result    where the text is to be appended
 * @param delegate notified of locations of sub fields
 * @return The formatted number string
 * @exception        ArithmeticException if rounding is needed with rounding
 *                   mode being set to RoundingMode.UNNECESSARY
 * @see java.text.FieldPosition
 */
private StringBuffer format(BigInteger number, StringBuffer result,
                           FieldDelegate delegate, boolean formatLong) {
    if (multiplier != 1) {
        number = number.multiply(getBigIntegerMultiplier());
    }
    boolean isNegative = number.signum() == -1;
    if (isNegative) {
        number = number.negate();
    }

    synchronized(digitList) {
        int maxIntDigits, minIntDigits, maxFraDigits, minFraDigits, maximumDigits;
        if (formatLong) {
            maxIntDigits = super.getMaximumIntegerDigits();
            minIntDigits = super.getMinimumIntegerDigits();
            maxFraDigits = super.getMaximumFractionDigits();
            minFraDigits = super.getMinimumFractionDigits();
            maximumDigits = maxIntDigits + maxFraDigits;
        } else {
            maxIntDigits = getMaximumIntegerDigits();
            minIntDigits = getMinimumIntegerDigits();
            maxFraDigits = getMaximumFractionDigits();
            minFraDigits = getMinimumFractionDigits();
            maximumDigits = maxIntDigits + maxFraDigits;
            if (maximumDigits < 0) {
                maximumDigits = Integer.MAX_VALUE;
            }
        }

        digitList.set(isNegative, number,
                      useExponentialNotation ? maximumDigits : 0);

        return subformat(result, delegate, isNegative, true,
            maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
    }
}
 
Example 16
Source Project: ripple-lib-java   File: Tnaf.java    License: ISC License 4 votes vote down vote up
/**
     * Calculates the Lucas Sequence elements <code>U<sub>k-1</sub></code> and
     * <code>U<sub>k</sub></code> or <code>V<sub>k-1</sub></code> and
     * <code>V<sub>k</sub></code>.
     * @param mu The parameter <code>&mu;</code> of the elliptic curve.
     * @param k The index of the second element of the Lucas Sequence to be
     * returned.
     * @param doV If set to true, computes <code>V<sub>k-1</sub></code> and
     * <code>V<sub>k</sub></code>, otherwise <code>U<sub>k-1</sub></code> and
     * <code>U<sub>k</sub></code>.
     * @return An array with 2 elements, containing <code>U<sub>k-1</sub></code>
     * and <code>U<sub>k</sub></code> or <code>V<sub>k-1</sub></code>
     * and <code>V<sub>k</sub></code>.
     */
    public static BigInteger[] getLucas(byte mu, int k, boolean doV)
    {
        if (!((mu == 1) || (mu == -1)))
        {
            throw new IllegalArgumentException("mu must be 1 or -1");
        }

        BigInteger u0;
        BigInteger u1;
        BigInteger u2;

        if (doV)
        {
            u0 = ECConstants.TWO;
            u1 = BigInteger.valueOf(mu);
        }
        else
        {
            u0 = ECConstants.ZERO;
            u1 = ECConstants.ONE;
        }

        for (int i = 1; i < k; i++)
        {
            // u2 = mu*u1 - 2*u0;
            BigInteger s = null;
            if (mu == 1)
            {
                s = u1;
            }
            else
            {
                // mu == -1
                s = u1.negate();
            }
            
            u2 = s.subtract(u0.shiftLeft(1));
            u0 = u1;
            u1 = u2;
//            System.out.println(i + ": " + u2);
//            System.out.println();
        }

        BigInteger[] retVal = {u0, u1};
        return retVal;
    }
 
Example 17
Source Project: 365browser   File: TextFormat.java    License: Apache License 2.0 4 votes vote down vote up
private static long parseInteger(final String text,
                                 final boolean isSigned,
                                 final boolean isLong)
                                 throws NumberFormatException {
  int pos = 0;

  boolean negative = false;
  if (text.startsWith("-", pos)) {
    if (!isSigned) {
      throw new NumberFormatException("Number must be positive: " + text);
    }
    ++pos;
    negative = true;
  }

  int radix = 10;
  if (text.startsWith("0x", pos)) {
    pos += 2;
    radix = 16;
  } else if (text.startsWith("0", pos)) {
    radix = 8;
  }

  final String numberText = text.substring(pos);

  long result = 0;
  if (numberText.length() < 16) {
    // Can safely assume no overflow.
    result = Long.parseLong(numberText, radix);
    if (negative) {
      result = -result;
    }

    // Check bounds.
    // No need to check for 64-bit numbers since they'd have to be 16 chars
    // or longer to overflow.
    if (!isLong) {
      if (isSigned) {
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
          throw new NumberFormatException(
            "Number out of range for 32-bit signed integer: " + text);
        }
      } else {
        if (result >= (1L << 32) || result < 0) {
          throw new NumberFormatException(
            "Number out of range for 32-bit unsigned integer: " + text);
        }
      }
    }
  } else {
    BigInteger bigValue = new BigInteger(numberText, radix);
    if (negative) {
      bigValue = bigValue.negate();
    }

    // Check bounds.
    if (!isLong) {
      if (isSigned) {
        if (bigValue.bitLength() > 31) {
          throw new NumberFormatException(
            "Number out of range for 32-bit signed integer: " + text);
        }
      } else {
        if (bigValue.bitLength() > 32) {
          throw new NumberFormatException(
            "Number out of range for 32-bit unsigned integer: " + text);
        }
      }
    } else {
      if (isSigned) {
        if (bigValue.bitLength() > 63) {
          throw new NumberFormatException(
            "Number out of range for 64-bit signed integer: " + text);
        }
      } else {
        if (bigValue.bitLength() > 64) {
          throw new NumberFormatException(
            "Number out of range for 64-bit unsigned integer: " + text);
        }
      }
    }

    result = bigValue.longValue();
  }

  return result;
}
 
Example 18
Source Project: ffwd   File: TextFormat.java    License: Apache License 2.0 4 votes vote down vote up
private static long parseInteger(final String text,
                                 final boolean isSigned,
                                 final boolean isLong)
                                 throws NumberFormatException {
  int pos = 0;

  boolean negative = false;
  if (text.startsWith("-", pos)) {
    if (!isSigned) {
      throw new NumberFormatException("Number must be positive: " + text);
    }
    ++pos;
    negative = true;
  }

  int radix = 10;
  if (text.startsWith("0x", pos)) {
    pos += 2;
    radix = 16;
  } else if (text.startsWith("0", pos)) {
    radix = 8;
  }

  final String numberText = text.substring(pos);

  long result = 0;
  if (numberText.length() < 16) {
    // Can safely assume no overflow.
    result = Long.parseLong(numberText, radix);
    if (negative) {
      result = -result;
    }

    // Check bounds.
    // No need to check for 64-bit numbers since they'd have to be 16 chars
    // or longer to overflow.
    if (!isLong) {
      if (isSigned) {
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
          throw new NumberFormatException(
            "Number out of range for 32-bit signed integer: " + text);
        }
      } else {
        if (result >= (1L << 32) || result < 0) {
          throw new NumberFormatException(
            "Number out of range for 32-bit unsigned integer: " + text);
        }
      }
    }
  } else {
    BigInteger bigValue = new BigInteger(numberText, radix);
    if (negative) {
      bigValue = bigValue.negate();
    }

    // Check bounds.
    if (!isLong) {
      if (isSigned) {
        if (bigValue.bitLength() > 31) {
          throw new NumberFormatException(
            "Number out of range for 32-bit signed integer: " + text);
        }
      } else {
        if (bigValue.bitLength() > 32) {
          throw new NumberFormatException(
            "Number out of range for 32-bit unsigned integer: " + text);
        }
      }
    } else {
      if (isSigned) {
        if (bigValue.bitLength() > 63) {
          throw new NumberFormatException(
            "Number out of range for 64-bit signed integer: " + text);
        }
      } else {
        if (bigValue.bitLength() > 64) {
          throw new NumberFormatException(
            "Number out of range for 64-bit unsigned integer: " + text);
        }
      }
    }

    result = bigValue.longValue();
  }

  return result;
}
 
Example 19
Source Project: astor   File: BigFraction.java    License: GNU General Public License v2.0 3 votes vote down vote up
/**
 * <p>
 * Returns a <code>BigFraction</code> whose value is
 * <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
 * </p>
 *
 * @param exponent
 *            exponent to which this <code>BigFraction</code> is to be raised.
 * @return <tt>this<sup>exponent</sup></tt> as a <code>BigFraction</code>.
 */
public BigFraction pow(final BigInteger exponent) {
    if (exponent.compareTo(BigInteger.ZERO) < 0) {
        final BigInteger eNeg = exponent.negate();
        return new BigFraction(ArithmeticUtils.pow(denominator, eNeg),
                               ArithmeticUtils.pow(numerator,   eNeg));
    }
    return new BigFraction(ArithmeticUtils.pow(numerator,   exponent),
                           ArithmeticUtils.pow(denominator, exponent));
}
 
Example 20
Source Project: astor   File: BigFraction.java    License: GNU General Public License v2.0 3 votes vote down vote up
/**
 * <p>
 * Returns a <code>BigFraction</code> whose value is
 * <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
 * </p>
 *
 * @param exponent
 *            exponent to which this <code>BigFraction</code> is to be raised.
 * @return <tt>this<sup>exponent</sup></tt> as a <code>BigFraction</code>.
 */
public BigFraction pow(final BigInteger exponent) {
    if (exponent.compareTo(BigInteger.ZERO) < 0) {
        final BigInteger eNeg = exponent.negate();
        return new BigFraction(MathUtils.pow(denominator, eNeg),
                               MathUtils.pow(numerator,   eNeg));
    }
    return new BigFraction(MathUtils.pow(numerator,   exponent),
                           MathUtils.pow(denominator, exponent));
}