Example usage for java.math BigInteger BigInteger

List of usage examples for java.math BigInteger BigInteger

Introduction

In this page you can find the example usage for java.math BigInteger BigInteger.

Prototype

private BigInteger(long val) 

Source Link

Document

Constructs a BigInteger with the specified value, which may not be zero.

Usage

From source file:info.archinnov.achilles.test.integration.tests.SupportedTypesIT.java

@Test
public void should_persist_and_find_all_types() throws Exception {
    // Given//from   w  w w .  j ava2s  .com
    Long id = RandomUtils.nextLong();
    byte[] bytes = "toto".getBytes(Charsets.UTF_8);
    Date now = new Date();
    InetAddress inetAddress = InetAddresses.forString("192.168.0.1");

    EntityWithAllTypes entity = new EntityWithAllTypes();
    entity.setId(id);

    entity.setPrimitiveByte((byte) 7);
    entity.setObjectByte((byte) 7);
    entity.setByteArray(bytes);
    entity.setByteBuffer(ByteBuffer.wrap(bytes));

    entity.setPrimitiveBool(true);
    entity.setObjectBool(true);

    entity.setDate(now);

    entity.setPrimitiveDouble(1.0d);
    entity.setObjectDouble(1.0d);
    entity.setBigDecimal(new BigDecimal(1.11));

    entity.setPrimitiveFloat(1.0f);
    entity.setObjectFloat(1.0f);

    entity.setInetAddress(inetAddress);

    entity.setBigInt(new BigInteger("10"));
    entity.setPrimitiveInt(10);
    entity.setObjectInt(10);

    entity.setPrimitiveLong(10L);

    // When
    manager.persist(entity);
    EntityWithAllTypes found = manager.find(EntityWithAllTypes.class, id);

    // Then
    assertThat(found.getPrimitiveByte()).isEqualTo((byte) 7);
    assertThat(found.getObjectByte()).isEqualTo((byte) 7);
    assertThat(found.getByteArray()).isEqualTo(bytes);
    assertThat(found.getByteBuffer()).isEqualTo(ByteBuffer.wrap(bytes));

    assertThat(found.isPrimitiveBool()).isTrue();
    assertThat(found.getObjectBool()).isTrue();

    assertThat(found.getDate()).isEqualTo(now);

    assertThat(found.getPrimitiveDouble()).isEqualTo(1.0d);
    assertThat(found.getObjectDouble()).isEqualTo(1.0d);
    assertThat(found.getBigDecimal()).isEqualTo(new BigDecimal(1.11));

    assertThat(found.getPrimitiveFloat()).isEqualTo(1.0f);
    assertThat(found.getObjectFloat()).isEqualTo(1.0f);

    assertThat(found.getInetAddress()).isEqualTo(inetAddress);

    assertThat(found.getBigInt()).isEqualTo(new BigInteger("10"));
    assertThat(found.getPrimitiveInt()).isEqualTo(10);
    assertThat(found.getObjectInt()).isEqualTo(10);

    assertThat(found.getPrimitiveLong()).isEqualTo(10L);
}

From source file:mitm.common.util.MiscArrayUtils.java

/**
 * Encodes the byte array to a String consisting of all readable characters.
 *///from   ww w  .j a  v  a  2s  . com
public static String toMaxRadix(byte[] bytes) {
    Check.notNull(bytes, "bytes");

    /*
     * We need to make sure that the BigInteger will be positive and that any starting zero (0) bytes
     * are not removed.
     */
    byte[] pos = ArrayUtils.addAll(new byte[] { 1 }, bytes);

    BigInteger bigInt = new BigInteger(pos);

    return bigInt.toString(Character.MAX_RADIX);
}

From source file:fi.koku.services.entity.kks.impl.KksConverter.java

public static KksEntryClassType toWsType(KksEntryClass entryClass) {
    KksEntryClassType kksEntryClassType = new KksEntryClassType();
    kksEntryClassType.setId("" + entryClass.getEntryClassId());
    kksEntryClassType.setDescription(entryClass.getDescription());
    kksEntryClassType.setDataType(entryClass.getDataType());
    kksEntryClassType.setGroupId("" + entryClass.getGroupId());
    kksEntryClassType.setMultiValue(entryClass.isMultiValue());
    kksEntryClassType.setName(entryClass.getName());
    kksEntryClassType.setSortOrder(new BigInteger("" + entryClass.getSortOrder()));
    KksTagsType kksTagsType = new KksTagsType();

    if (entryClass.getTags() != null) {
        for (KksTag tag : entryClass.getTags()) {
            KksTagType t = new KksTagType();
            t.setId("" + tag.getTagId());
            t.setName(tag.getName());//from   w w  w . j  a  v a 2s  .  c o m
            t.setDescription(tag.getDescription());
            kksTagsType.getKksTag().add(t);
        }
    }

    kksEntryClassType.setKksTags(kksTagsType);

    ValueSpacesType valueSpacesType = new ValueSpacesType();

    if (entryClass.getValueSpaces() != null) {
        String tmp[] = entryClass.getValueSpaces().split(",");
        for (String s : tmp) {
            valueSpacesType.getValueSpace().add(s.trim());
        }
    } else {
        valueSpacesType.getValueSpace().add("");
    }

    kksEntryClassType.setValueSpaces(valueSpacesType);
    return kksEntryClassType;
}

From source file:org.osiam.resource_server.storage.helper.NumberPadder.java

/**
 * Adds an offset and padding to a number
 *
 * @param value//from  w  w  w .j  a va 2 s  .  c  om
 *            the number as {@link String}
 * @return the padded string with the added offset.
 */
public String pad(String value) {
    String integralPart = value;
    String fractionalPart = "";

    if (value.contains(".")) {
        int indexOfDecimalSeparator = value.indexOf('.');
        integralPart = value.substring(0, indexOfDecimalSeparator);
        fractionalPart = value.substring(indexOfDecimalSeparator);
    }

    // The max allowed length of the integral part depends on the presence of a '-' as first character.
    // If it is present 21 characters are allowed, otherwise 20 (This is done by applying indexOf magic).
    if (integralPart.length() > (PAD_LENGTH + integralPart.indexOf('-'))) {
        throw new IllegalArgumentException("The given value has more than " + (PAD_LENGTH - 1) + " digits.");
    }

    integralPart = new BigInteger(integralPart).add(BIG_OFFSET).toString();
    integralPart = Strings.padStart(integralPart, PAD_LENGTH, '0');

    return integralPart + fractionalPart;
}

From source file:com.aegiswallet.objects.SMSTransactionPojo.java

public SMSTransactionPojo(String base64EncodedJSONString) {
    byte[] decoded = Base64.decode(base64EncodedJSONString.getBytes(), Base64.NO_WRAP);
    String jsonString = new String(decoded);

    try {/*from  www . j a  v  a2  s .c  om*/
        JSONObject object = new JSONObject(jsonString);

        this.phoneNumber = object.getString("number");
        this.name = object.getString("name");
        this.amount = new BigInteger(object.getString("amount"));
        this.btcAddress = object.getString("address");
        this.timestamp = new Long(object.getString("timestamp")).longValue();
        this.status = new Integer(object.getString("status")).intValue();
        this.tag = object.getString("tag");

    } catch (JSONException e) {
        Log.d(TAG, e.getMessage());
    }
}

From source file:co.rsk.peg.SamplePrecompiledContractTest.java

@Test
public void samplePrecompiledContractMethod1Ok() {
    DataWord addr = new DataWord(PrecompiledContracts.SAMPLE_ADDR);
    SamplePrecompiledContract contract = (SamplePrecompiledContract) PrecompiledContracts
            .getContractForAddress(addr);

    String funcJson = "{\n" + "   'constant':false, \n" + "   'inputs':[{'name':'param0','type':'int'}, \n"
            + "               {'name':'param1','type':'bytes'}, \n"
            + "               {'name':'param2','type':'int'}], \n" + "    'name':'Method1', \n"
            + "   'outputs':[{'name':'output0','type':'int'}], \n" + "    'type':'function' \n" + "}\n";
    funcJson = funcJson.replaceAll("'", "\"");

    CallTransaction.Function function = CallTransaction.Function.fromJsonInterface(funcJson);

    byte[] bytes = new byte[] { (byte) 0xab, (byte) 0xcd, (byte) 0xef };
    byte[] data = function.encode(111, bytes, 222);

    contract.init(null, null, new RepositoryImpl(), null, null, new ArrayList<LogInfo>());
    byte[] result = contract.execute(data);

    Object[] results = function.decodeResult(result);
    assertEquals(new BigInteger("1"), results[0]);
}

From source file:edu.internet2.middleware.openid.message.impl.AssociationRequestUnmarshaller.java

/** {@inheritDoc} */
public void unmarshallParameters(AssociationRequest request, ParameterMap parameters)
        throws UnmarshallingException {

    SessionType sessionType = SessionType.getType(parameters.get(Parameter.session_type.QNAME));
    request.setAssociationType(AssociationType.getType(parameters.get(Parameter.assoc_type.QNAME)));

    if (sessionType != null) {
        request.setSessionType(sessionType);

        if (sessionType.equals(SessionType.DH_SHA1) || sessionType.equals(SessionType.DH_SHA256)) {

            String encodedGen = parameters.get(Parameter.dh_gen.QNAME);
            String encodedModulus = parameters.get(Parameter.dh_modulus.QNAME);

            BigInteger gen;//from  w ww  . j a v a2 s  . c o m
            if (!DatatypeHelper.isEmpty(encodedGen)) {
                gen = new BigInteger(Base64.decodeBase64(encodedGen.getBytes()));
            } else {
                gen = OpenIDConstants.DEFAULT_DH_GEN;
            }

            BigInteger modulus;
            if (!DatatypeHelper.isEmpty(encodedModulus)) {
                modulus = new BigInteger(Base64.decodeBase64(encodedModulus.getBytes()));
            } else {
                modulus = OpenIDConstants.DEFAULT_DH_MODULUS;
            }

            DHParameterSpec dhParameters = new DHParameterSpec(modulus, gen);
            request.setDHParameters(dhParameters);

            String encodedKey = parameters.get(Parameter.dh_consumer_public.QNAME);
            if (!DatatypeHelper.isEmpty(encodedKey)) {
                try {
                    DHPublicKey publicKey = EncodingUtils.decodePublicKey(encodedKey, dhParameters);
                    request.setDHConsumerPublic(publicKey);
                } catch (NoSuchAlgorithmException e) {
                    throw new UnmarshallingException(e);
                } catch (InvalidKeySpecException e) {
                    throw new UnmarshallingException(e);
                }
            }

        }
    }

}

From source file:cc.redberry.core.number.Exponentiation.java

static BigInteger findIntegerRoot(BigInteger base, BigInteger power) {
    BigInteger maxBits = BigInteger.valueOf(base.bitLength() + 1); // base < 2 ^ (maxBits + 1)
    // => base ^ ( 1 / power ) < 2 ^ ( (maxBits + 1) / power )

    BigInteger[] divResult = maxBits.divideAndRemainder(power);
    if (divResult[1].signum() == 0) // i.e. divResult[1] == 0
        maxBits = divResult[0];/*from w  w w. j a  va 2  s.c  o  m*/
    else
        maxBits = divResult[0].add(BigInteger.ONE);

    if (maxBits.bitLength() > 31)
        throw new RuntimeException("Too many bits...");

    int targetBitsNumber = maxBits.intValue();
    int resultLengthM1 = targetBitsNumber / 8 + 1; //resultLength minus one
    byte[] result = new byte[resultLengthM1];
    resultLengthM1--;

    int bitNumber = targetBitsNumber;

    int cValue;
    BigInteger testValue;

    while ((--bitNumber) >= 0) {
        //setting bit
        result[resultLengthM1 - (bitNumber >> 3)] |= 1 << (bitNumber & 0x7);

        //Testing
        testValue = new BigInteger(result);
        cValue = ArithmeticUtils.pow(testValue, power).compareTo(base);
        if (cValue == 0)
            return testValue;
        if (cValue > 0)
            result[resultLengthM1 - (bitNumber >> 3)] &= ~(1 << (bitNumber & 0x7));
    }

    return null;
}

From source file:edu.wisc.hr.demo.RandomLeaveStatementDao.java

@Override
public Collection<SummarizedLeaveStatement> getLeaveStatements(String emplid) {

    if (emplIdToSummarizedLeaveStatements.containsKey(emplid)) {
        return emplIdToSummarizedLeaveStatements.get(emplid);
    }//from ww  w  . j  av  a 2s.co  m

    int howManyLeaveStatements = random.nextInt(20);

    List<String> payPeriodLabels = payPeriodGenerator.payPeriods(howManyLeaveStatements);

    Collection<SummarizedLeaveStatement> leaveStatements = new LinkedList<SummarizedLeaveStatement>();

    for (String payPeriodLabel : payPeriodLabels) {

        SummarizedLeaveStatement leaveStatement = new SummarizedLeaveStatement();

        BigInteger randomDocId = new BigInteger(Integer.toString(random.nextInt()));
        leaveStatement.setLeaveStatementDocId(randomDocId);

        leaveStatement.setLeaveStatementTitle("What's a leave statement title?");

        leaveStatement.setPayPeriod(payPeriodLabel);

        int howManyFurloughReports = random.nextInt(4);

        for (int i = 0; i < howManyFurloughReports; i++) {

            Report report = new Report();
            report.setTitle("What's a furlough report title?");

            BigInteger randomDocIdForFurlough = new BigInteger(Integer.toString(random.nextInt()));
            report.setDocId(randomDocIdForFurlough);

            leaveStatement.getLeaveFurloughReports().add(report);
        }

        int howManyMissingLeaveReports = random.nextInt(4);

        for (int i = 0; i < howManyMissingLeaveReports; i++) {

            Report report = new Report();
            report.setTitle("What's a missing leave report title?");

            BigInteger randomDocIdForFurlough = new BigInteger(Integer.toString(random.nextInt()));
            report.setDocId(randomDocIdForFurlough);

            leaveStatement.getMissingReports().add(report);
        }

        leaveStatements.add(leaveStatement);
    }

    this.emplIdToSummarizedLeaveStatements.put(emplid, leaveStatements);

    return leaveStatements;
}

From source file:bftsmart.consensus.TimestampValuePair.java

@Override
public int hashCode() {
    int hash = 1;
    hash = hash * 17 + timestamp;/*from w  w  w. ja v a2 s . c  o m*/
    hash = hash * 31 + (new BigInteger(value)).intValue();
    return hash;
}