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

The following examples show how to use java.math.BigInteger#valueOf() . 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: aion   File: Value.java    License: MIT License 6 votes vote down vote up
/**
 * @return the numerical value as a {@link BigInteger}. If called for values that are not
 *     numbers or byte arrays it will return {@link BigInteger#ZERO}.
 */
public BigInteger asBigInt() {
    decode();
    if (value instanceof BigInteger) {
        return (BigInteger) value;
    } else if (isBytes()) {
        return new BigInteger(1, asBytes());
    } else if (value instanceof Byte) {
        return BigInteger.valueOf((Byte) value);
    } else if (value instanceof Short) {
        return BigInteger.valueOf((Short) value);
    } else if (value instanceof Integer) {
        return BigInteger.valueOf((Integer) value);
    } else if (value instanceof Long) {
        return BigInteger.valueOf((Long) value);
    }
    return BigInteger.ZERO;
}
 
Example 2
public static void bitCount() {
    int failCount = 0;

    for (int i=0; i<SIZE*10; i++) {
        int x = rnd.nextInt();
        BigInteger bigX = BigInteger.valueOf((long)x);
        int bit = (x < 0 ? 0 : 1);
        int tmp = x, bitCount = 0;
        for (int j=0; j<32; j++) {
            bitCount += ((tmp & 1) == bit ? 1 : 0);
            tmp >>= 1;
        }

        if (bigX.bitCount() != bitCount) {
            //System.err.println(x+": "+bitCount+", "+bigX.bitCount());
            failCount++;
        }
    }
    report("Bit Count", failCount);
}
 
Example 3
Source Project: aion   File: RLPSpecExtraTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testEncodeLong4() {
    long input = 4295000060L;
    byte[] expected = Hex.decode("850100007ffc");

    byte[] actual = RLP.encode(input);
    assertThat(actual).isEqualTo(expected);

    actual = RLP.encodeLong(input);
    assertThat(actual).isEqualTo(Hex.decode("880000000100007ffc"));

    BigInteger inputBI = BigInteger.valueOf(input);

    actual = RLP.encode(inputBI);
    assertThat(actual).isEqualTo(expected);

    actual = RLP.encodeBigInteger(inputBI);
    assertThat(actual).isEqualTo(expected);

    byte[] inputAsBytes =
            input == 0 ? EMPTY_BYTE_ARRAY : asUnsignedByteArray(BigInteger.valueOf(input));
    assertThat(RLP.calcElementPrefixSize(inputAsBytes)).isEqualTo(1);

    assertThat(RLP.encodeLongElementHeader(inputAsBytes.length)).isEqualTo(Hex.decode("85"));
}
 
Example 4
Source Project: OSPREY3   File: ConfSpace.java    License: GNU General Public License v2.0 5 votes vote down vote up
public BigInteger getNumConformations() {
	BigInteger count = BigInteger.valueOf(1);
	for (int pos=0; pos<numPos; pos++) {
		count = count.multiply(BigInteger.valueOf(posFlex.get(pos).RCs.size()));
	}
	return count;
}
 
Example 5
public void testToStandardWeeks() {
    Period test = new Period(0, 0, 3, 4, 5, 6, 7, 8);
    assertEquals(3, test.toStandardWeeks().getWeeks());
    
    test = new Period(0, 0, 3, 7, 0, 0, 0, 0);
    assertEquals(4, test.toStandardWeeks().getWeeks());
    
    test = new Period(0, 0, 0, 6, 23, 59, 59, 1000);
    assertEquals(1, test.toStandardWeeks().getWeeks());
    
    test = new Period(0, 0, Integer.MAX_VALUE, 0, 0, 0, 0, 0);
    assertEquals(Integer.MAX_VALUE, test.toStandardWeeks().getWeeks());
    
    test = new Period(0, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE);
    long intMax = Integer.MAX_VALUE;
    BigInteger expected = BigInteger.valueOf(intMax);
    expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_SECOND));
    expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_MINUTE));
    expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_HOUR));
    expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_DAY));
    expected = expected.divide(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_WEEK));
    assertTrue(expected.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) < 0);
    assertEquals(expected.longValue(), test.toStandardWeeks().getWeeks());
    
    test = new Period(0, 0, Integer.MAX_VALUE, 7, 0, 0, 0, 0);
    try {
        test.toStandardWeeks();
        fail();
    } catch (ArithmeticException ex) {}
}
 
Example 6
/**
 * <p>Constructor of value spaces that a
 * <code>java.util.GregorianCalendar</code> instance would need to convert to an
 * <code>XMLGregorianCalendar</code> instance.</p>
 *
 * <p><code>XMLGregorianCalendar eon</code> and
 * <code>fractionalSecond</code> are set to <code>null</code></p>
 *
 * <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.</p>
 *
 * @param year of <code>XMLGregorianCalendar</code> to be created.
 * @param month of <code>XMLGregorianCalendar</code> to be created.
 * @param day of <code>XMLGregorianCalendar</code> to be created.
 * @param hour of <code>XMLGregorianCalendar</code> to be created.
 * @param minute of <code>XMLGregorianCalendar</code> to be created.
 * @param second of <code>XMLGregorianCalendar</code> to be created.
 * @param millisecond of <code>XMLGregorianCalendar</code> to be created.
 * @param timezone of <code>XMLGregorianCalendar</code> to be created.
 *
 * @return <code>XMLGregorianCalendar</code> created from specified values.
 *
 * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
 *   as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
 *   or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
 *   as determined by {@link XMLGregorianCalendar#isValid()}.
 */
public XMLGregorianCalendar newXMLGregorianCalendar(
        final int year,
        final int month,
        final int day,
        final int hour,
        final int minute,
        final int second,
        final int millisecond,
        final int timezone) {

        // year may be undefined
        BigInteger realYear = (year != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) year) : null;

        // millisecond may be undefined
        // millisecond must be >= 0 millisecond <= 1000
        BigDecimal realMillisecond = null; // undefined value
        if (millisecond != DatatypeConstants.FIELD_UNDEFINED) {
                if (millisecond < 0 || millisecond > 1000) {
                        throw new IllegalArgumentException(
                                                "javax.xml.datatype.DatatypeFactory#newXMLGregorianCalendar("
                                                + "int year, int month, int day, int hour, int minute, int second, int millisecond, int timezone)"
                                                + "with invalid millisecond: " + millisecond
                                                );
                }

                realMillisecond = BigDecimal.valueOf((long) millisecond).movePointLeft(3);
        }

        return newXMLGregorianCalendar(
                realYear,
                month,
                day,
                hour,
                minute,
                second,
                realMillisecond,
                timezone
        );
}
 
Example 7
Source Project: api   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] argv) {
    System.out.println(System.currentTimeMillis());
    BigInteger bi = BigInteger.valueOf(1557849267933L);
    System.out.println(java.util.Arrays.toString((bi.toByteArray())));

    System.out.println(java.util.Arrays.toString(toByteArrayLittleEndianUnsigned(bi)));

    System.out.println(Arrays.toString(bnToU8a(bi, false, true, 64)));
    System.out.println(Arrays.toString(bnToU8a(bi, true, true, 64)));
}
 
Example 8
Source Project: web3sdk   File: Int112.java    License: Apache License 2.0 4 votes vote down vote up
public Int112(long value) {
    this(BigInteger.valueOf(value));
}
 
Example 9
private BigInteger getGasPrice(){
    return BigInteger.valueOf(Long.valueOf(mValueGasPrice));
}
 
Example 10
/**
 * Format a long to produce a string.
 * @param number    The long 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(long number, StringBuffer result,
                           FieldDelegate delegate) {
    boolean isNegative = (number < 0);
    if (isNegative) {
        number = -number;
    }

    // In general, long values always represent real finite numbers, so
    // we don't have to check for +/- Infinity or NaN.  However, there
    // is one case we have to be careful of:  The multiplier can push
    // a number near MIN_VALUE or MAX_VALUE outside the legal range.  We
    // check for this before multiplying, and if it happens we use
    // BigInteger instead.
    boolean useBigInteger = false;
    if (number < 0) { // This can only happen if number == Long.MIN_VALUE.
        if (multiplier != 0) {
            useBigInteger = true;
        }
    } else if (multiplier != 1 && multiplier != 0) {
        long cutoff = Long.MAX_VALUE / multiplier;
        if (cutoff < 0) {
            cutoff = -cutoff;
        }
        useBigInteger = (number > cutoff);
    }

    if (useBigInteger) {
        if (isNegative) {
            number = -number;
        }
        BigInteger bigIntegerValue = BigInteger.valueOf(number);
        return format(bigIntegerValue, result, delegate, true);
    }

    number *= multiplier;
    if (number == 0) {
        isNegative = false;
    } else {
        if (multiplier < 0) {
            number = -number;
            isNegative = !isNegative;
        }
    }

    synchronized(digitList) {
        int maxIntDigits = super.getMaximumIntegerDigits();
        int minIntDigits = super.getMinimumIntegerDigits();
        int maxFraDigits = super.getMaximumFractionDigits();
        int minFraDigits = super.getMinimumFractionDigits();

        digitList.set(isNegative, number,
                 useExponentialNotation ? maxIntDigits + maxFraDigits : 0);

        return subformat(result, delegate, isNegative, true,
                   maxIntDigits, minIntDigits, maxFraDigits, minFraDigits);
    }
}
 
Example 11
public Uint224(long value) {
    this(BigInteger.valueOf(value));
}
 
Example 12
public void main(Provider p) throws Exception {
    long start = System.currentTimeMillis();
    provider = p;
    data = new byte[2048];
    // keypair generation is very slow, test only a few short keys
    int[] keyLengths = {512, 512, 1024};
    BigInteger[] pubExps = {null, BigInteger.valueOf(3), null};
    KeyPair[] keyPairs = new KeyPair[3];
    new Random().nextBytes(data);
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", provider);
    for (int i = 0; i < keyLengths.length; i++) {
        int len = keyLengths[i];
        BigInteger exp = pubExps[i];
        System.out.println("Generating " + len + " bit keypair...");
        if (exp == null) {
            kpg.initialize(len);
        } else {
            kpg.initialize(new RSAKeyGenParameterSpec(len, exp));
        }
        KeyPair kp = kpg.generateKeyPair();
        keyPairs[i] = kp;
        RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic();
        System.out.println(publicKey);
        RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey)kp.getPrivate();
        if (publicKey.getModulus().equals(privateKey.getModulus()) == false) {
            throw new Exception("Moduli do not match");
        }
        if (publicKey.getPublicExponent().equals(privateKey.getPublicExponent()) == false) {
            throw new Exception("Exponents do not match");
        }
        int keyLen = publicKey.getModulus().bitLength();
        if ((keyLen > len) || (keyLen < len - 1)) {
            throw new Exception("Incorrect key length: " + keyLen);
        }
        if (exp != null) {
            if (exp.equals(publicKey.getPublicExponent()) == false) {
                throw new Exception("Incorrect exponent");
            }
        }
        test(privateKey, publicKey);
    }
    testInvalidSignature(keyPairs[0], keyPairs[1]);
    testInvalidSignature(keyPairs[0], keyPairs[2]);
    long stop = System.currentTimeMillis();
    System.out.println("All tests passed (" + (stop - start) + " ms).");
}
 
Example 13
Source Project: web3j   File: Uint256.java    License: Apache License 2.0 4 votes vote down vote up
public Uint256(long value) {
    this(BigInteger.valueOf(value));
}
 
Example 14
Source Project: web3sdk   File: Int24.java    License: Apache License 2.0 4 votes vote down vote up
public Int24(long value) {
    this(BigInteger.valueOf(value));
}
 
Example 15
Source Project: SAMLRaider   File: BurpCertificateBuilder.java    License: MIT License 4 votes vote down vote up
public void setSerial(int serial) {
	this.serial = BigInteger.valueOf(serial);
}
 
Example 16
@ParameterizedTest
@EnumSource(RepositoryType.class)
public void addMetadataToAccount(RepositoryType type) {
    BigInteger key = BigInteger.valueOf(RandomUtils.generateRandomInt(100000));

    String message = "This is the message for this account! 汉字" + key;
    System.out.println(
        "Storing message '" + message + "' in account metadata " + testAccount.getAddress()
            .plain());

    AccountMetadataTransaction transaction =
        AccountMetadataTransactionFactory.create(
            getNetworkType(), testAccount.getAddress(),
            key,
            message
        ).maxFee(this.maxFee).build();

    AccountMetadataTransaction processedTransaction = announceAggregateAndValidate(type,
        transaction, testAccount).getLeft();

    Assertions.assertEquals(transaction.getValueSizeDelta(),
        processedTransaction.getValueSizeDelta());

    Assertions.assertEquals(transaction.getScopedMetadataKey(),
        processedTransaction.getScopedMetadataKey());

    sleep(1000);

    Metadata metadata = assertMetadata(transaction,
        get(getRepositoryFactory(type).createMetadataRepository()
            .getAccountMetadata(testAccount.getAddress(),
                Optional.empty())));

    assertMetadata(transaction, get(getRepositoryFactory(type).createMetadataRepository()
        .getAccountMetadataByKey(testAccount.getAddress(),
            metadata.getMetadataEntry().getScopedMetadataKey())));

    assertMetadata(transaction,
        Collections.singletonList(get(getRepositoryFactory(type).createMetadataRepository()
            .getAccountMetadataByKeyAndSender(testAccount.getAddress(), key,
                testAccount.getAddress()))));

    Assertions.assertEquals(message, processedTransaction.getValue());
}
 
Example 17
Source Project: astor   File: BigFraction.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a fraction given the double value and either the maximum error
 * allowed or the maximum number of denominator digits.
 * <p>
 *
 * NOTE: This constructor is called with EITHER - a valid epsilon value and
 * the maxDenominator set to Integer.MAX_VALUE (that way the maxDenominator
 * has no effect). OR - a valid maxDenominator value and the epsilon value
 * set to zero (that way epsilon only has effect if there is an exact match
 * before the maxDenominator value is reached).
 * </p>
 * <p>
 *
 * It has been done this way so that the same code can be (re)used for both
 * scenarios. However this could be confusing to users if it were part of
 * the public API and this constructor should therefore remain PRIVATE.
 * </p>
 *
 * See JIRA issue ticket MATH-181 for more details:
 *
 * https://issues.apache.org/jira/browse/MATH-181
 *
 * @param value
 *            the double value to convert to a fraction.
 * @param epsilon
 *            maximum error allowed. The resulting fraction is within
 *            <code>epsilon</code> of <code>value</code>, in absolute terms.
 * @param maxDenominator
 *            maximum denominator value allowed.
 * @param maxIterations
 *            maximum number of convergents.
 * @throws FractionConversionException
 *             if the continued fraction failed to converge.
 */
private BigFraction(final double value, final double epsilon,
                    final int maxDenominator, int maxIterations)
    throws FractionConversionException {
    long overflow = Integer.MAX_VALUE;
    double r0 = value;
    long a0 = (long) Math.floor(r0);
    if (a0 > overflow) {
        throw new FractionConversionException(value, a0, 1l);
    }

    // check for (almost) integer arguments, which should not go
    // to iterations.
    if (Math.abs(a0 - value) < epsilon) {
        numerator = BigInteger.valueOf(a0);
        denominator = BigInteger.ONE;
        return;
    }

    long p0 = 1;
    long q0 = 0;
    long p1 = a0;
    long q1 = 1;

    long p2 = 0;
    long q2 = 1;

    int n = 0;
    boolean stop = false;
    do {
        ++n;
        final double r1 = 1.0 / (r0 - a0);
        final long a1 = (long) Math.floor(r1);
        p2 = (a1 * p1) + p0;
        q2 = (a1 * q1) + q0;
        if ((p2 > overflow) || (q2 > overflow)) {
            throw new FractionConversionException(value, p2, q2);
        }

        final double convergent = (double) p2 / (double) q2;
        if ((n < maxIterations) &&
            (Math.abs(convergent - value) > epsilon) &&
            (q2 < maxDenominator)) {
            p0 = p1;
            p1 = p2;
            q0 = q1;
            q1 = q2;
            a0 = a1;
            r0 = r1;
        } else {
            stop = true;
        }
    } while (!stop);

    if (n >= maxIterations) {
        throw new FractionConversionException(value, maxIterations);
    }

    if (q2 < maxDenominator) {
        numerator   = BigInteger.valueOf(p2);
        denominator = BigInteger.valueOf(q2);
    } else {
        numerator   = BigInteger.valueOf(p1);
        denominator = BigInteger.valueOf(q1);
    }
}
 
Example 18
Source Project: IPAddress   File: IPv4AddressSection.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected BigInteger getPrefixCountImpl() {
	return BigInteger.valueOf(getIPv4PrefixCount());
}
 
Example 19
Source Project: lams   File: FileUtils.java    License: GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns the size of the specified file or directory. If the provided
 * {@link File} is a regular file, then the file's length is returned.
 * If the argument is a directory, then the size of the directory is
 * calculated recursively. If a directory or subdirectory is security
 * restricted, its size will not be included.
 *
 * @param file the regular file or directory to return the size
 *             of (must not be {@code null}).
 *
 * @return the length of the file, or recursive size of the directory,
 * provided (in bytes).
 *
 * @throws NullPointerException     if the file is {@code null}
 * @throws IllegalArgumentException if the file does not exist.
 *
 * @since 2.4
 */
public static BigInteger sizeOfAsBigInteger(final File file) {

    if (!file.exists()) {
        final String message = file + " does not exist";
        throw new IllegalArgumentException(message);
    }

    if (file.isDirectory()) {
        return sizeOfDirectoryBig0(file); // internal method
    } else {
        return BigInteger.valueOf(file.length());
    }

}
 
Example 20
Source Project: coming   File: BigFraction_s.java    License: MIT License 2 votes vote down vote up
/**
 * <p>
 * Create a {@link BigFraction} equivalent to the passed long, ie "num / 1".
 * </p>
 *
 * @param num
 *            the numerator.
 */
public BigFraction(final long num) {
    this(BigInteger.valueOf(num), BigInteger.ONE);
}