Example usage for java.math BigInteger add

List of usage examples for java.math BigInteger add

Introduction

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

Prototype

BigInteger add(long val) 

Source Link

Document

Package private methods used by BigDecimal code to add a BigInteger with a long.

Usage

From source file:org.apache.accumulo.master.tableOps.Utils.java

static String getNextTableId(String tableName, Instance instance) throws ThriftTableOperationException {

    String tableId = null;/*  w w  w. j  av a  2  s  .c o m*/
    try {
        IZooReaderWriter zoo = ZooReaderWriter.getRetryingInstance();
        final String ntp = ZooUtil.getRoot(instance) + Constants.ZTABLES;
        byte[] nid = zoo.mutate(ntp, ZERO_BYTE, ZooUtil.PUBLIC, new Mutator() {
            @Override
            public byte[] mutate(byte[] currentValue) throws Exception {
                BigInteger nextId = new BigInteger(new String(currentValue, Constants.UTF8),
                        Character.MAX_RADIX);
                nextId = nextId.add(BigInteger.ONE);
                return nextId.toString(Character.MAX_RADIX).getBytes(Constants.UTF8);
            }
        });
        return new String(nid, Constants.UTF8);
    } catch (Exception e1) {
        Logger.getLogger(CreateTable.class).error("Failed to assign tableId to " + tableName, e1);
        throw new ThriftTableOperationException(tableId, tableName, TableOperation.CREATE,
                TableOperationExceptionType.OTHER, e1.getMessage());
    }
}

From source file:Main.java

/**
 * Compute the square root of x to a given scale, x >= 0. Use Newton's
 * algorithm.//from w ww  . j  av a2 s .c  om
 * 
 * @param x
 *            the value of x
 * @return the result value
 */
public static BigDecimal sqrt(BigDecimal x) {
    // Check that x >= 0.
    if (x.signum() < 0) {
        throw new ArithmeticException("x < 0");
    }

    // n = x*(10^(2*SCALE))
    BigInteger n = x.movePointRight(SCALE << 1).toBigInteger();

    // The first approximation is the upper half of n.
    int bits = (n.bitLength() + 1) >> 1;
    BigInteger ix = n.shiftRight(bits);
    BigInteger ixPrev;

    // Loop until the approximations converge
    // (two successive approximations are equal after rounding).
    do {
        ixPrev = ix;

        // x = (x + n/x)/2
        ix = ix.add(n.divide(ix)).shiftRight(1);

        Thread.yield();
    } while (ix.compareTo(ixPrev) != 0);

    return new BigDecimal(ix, SCALE);
}

From source file:ID.java

public static String getHexString(byte[] bytes) {
    // This method cannot change even if it's wrong.
    BigInteger bigInteger = BigInteger.ZERO;
    int shift = 0;
    for (int i = bytes.length; --i >= 0;) {
        BigInteger contrib = BigInteger.valueOf(bytes[i] & 0xFF);
        contrib = contrib.shiftLeft(shift);
        bigInteger = bigInteger.add(contrib);
        shift += 8;/*from  w  w w  .  jav a 2  s .c  om*/
    }
    return bigInteger.toString(16).toUpperCase();
}

From source file:com.offbynull.peernetic.common.identification.Id.java

/**
 * Subtracts two IDs. The limit of the IDs must match.
 * @param lhs left-hand side/*from  w  ww. j av  a  2s . c  om*/
 * @param rhs right-hand side
 * @return {@code lhs - rhs}, wrapped around limit if it goes below {@code 0}
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if the limit from {@code lhs} doesn't match the limit from {@code rhs}
 */
public static Id subtract(Id lhs, Id rhs) {
    Validate.notNull(lhs);
    Validate.notNull(rhs);
    Validate.isTrue(lhs.limit.equals(rhs.limit));

    BigInteger subtracted = lhs.data.subtract(rhs.data);
    if (subtracted.signum() == -1) {
        subtracted = subtracted.add(lhs.limit).add(BigInteger.ONE);
    }

    Id subtractedId = new Id(subtracted, lhs.limit);

    return subtractedId;
}

From source file:Main.java

public static byte[] base58ToBytes(String value) {
    BigInteger bigNum58 = new BigInteger("58");
    BigInteger tempBigValue = new BigInteger("0");
    int leadingZeroes = 0;
    boolean justStarted = true;
    for (int i = 0; i < value.length(); i++) {
        if (justStarted && value.toCharArray()[i] == '1') {
            leadingZeroes++;//from  w  w w . j ava2  s  . c o m
        } else {
            justStarted = false;
            tempBigValue = tempBigValue.add(bigNum58.pow(value.length() - i - 1)
                    .multiply(new BigInteger("" + base58Array.indexOf(value.toCharArray()[i]))));
        }
    }
    byte[] bigValue = tempBigValue.toByteArray();
    int bigValueStart = 0;
    for (int j = 0; j < bigValue.length; j++) {
        if (bigValue[j] != 0) {
            bigValueStart = j;
            break;
        }
    }
    byte[] byteResult = new byte[bigValue.length + leadingZeroes - bigValueStart];
    for (int i = 0; i < byteResult.length; i++) {
        if (i - leadingZeroes + bigValueStart < bigValue.length && i - leadingZeroes + bigValueStart >= 0)
            byteResult[i] = i < leadingZeroes ? 0 : bigValue[i - leadingZeroes + bigValueStart];
    }
    return byteResult;
}

From source file:ac.elements.parser.SimpleDBConverter.java

/**
 * Decodes zero-padded positive long value from the string representation
 * //from   w  w w.j av  a  2 s .c  o  m
 * com.xerox.amazonws.sdb.DataUtils
 * 
 * @param value
 *            zero-padded string representation of the long
 * @return original long value
 */
private static long decodeLong(String value) {
    BigInteger bi = new BigInteger(value, RADIX);
    bi = bi.add(BigInteger.valueOf(Long.MIN_VALUE));
    return bi.longValue();
}

From source file:Main.java

/**
 * Java runtime 1.5 is inconsistent with its handling of days in Duration objects.
 * @param duration A duration object to be normalised
 * @return A day-normalised duration, i.e. all years and months converted to days,
 * e.g. 1Y 3M 3D => 458 days//from www . java2 s. c o m
 */
private static javax.xml.datatype.Duration normaliseDays(javax.xml.datatype.Duration duration) {
    final long DAYS_PER_MONTH = 30;
    final long DAYS_PER_YEAR = 365;

    BigInteger days = (BigInteger) duration.getField(DatatypeConstants.DAYS);
    BigInteger months = (BigInteger) duration.getField(DatatypeConstants.MONTHS);
    BigInteger years = (BigInteger) duration.getField(DatatypeConstants.YEARS);

    BigInteger normalisedDays = years.multiply(BigInteger.valueOf(DAYS_PER_YEAR));
    normalisedDays = normalisedDays.add(months.multiply(BigInteger.valueOf(DAYS_PER_MONTH)));
    normalisedDays = normalisedDays.add(days);

    BigInteger hours = (BigInteger) duration.getField(DatatypeConstants.HOURS);
    BigInteger minutes = (BigInteger) duration.getField(DatatypeConstants.MINUTES);
    BigDecimal seconds = (BigDecimal) duration.getField(DatatypeConstants.SECONDS);

    boolean positive = duration.getSign() >= 0;

    return FACTORY.newDuration(positive, BigInteger.ZERO, BigInteger.ZERO, normalisedDays, hours, minutes,
            seconds);
}

From source file:com.amazonaws.services.kinesis.clientlibrary.proxies.util.KinesisLocalFileDataCreator.java

/** Helper method to create a list of shards (which can then be used to generate data files).
 * @param numShards Number of shards/*from ww  w.  jav  a  2 s .  c  o  m*/
 * @param shardIdPrefix Prefix for the shardIds
 * @param startingSequenceNumber Starting sequence number for all the shards
 * @return List of shards (with no reshard events).
 */
public static List<Shard> createShardList(int numShards, String shardIdPrefix,
        BigInteger startingSequenceNumber) {
    List<Shard> shards = new ArrayList<Shard>(numShards);

    SequenceNumberRange sequenceNumberRange = new SequenceNumberRange();
    sequenceNumberRange.setStartingSequenceNumber(startingSequenceNumber.toString());
    sequenceNumberRange.setEndingSequenceNumber(null);
    BigInteger perShardHashKeyRange = KinesisLocalFileProxy.MAX_HASHKEY_VALUE
            .divide(new BigInteger(Integer.toString(numShards)));
    BigInteger hashKeyRangeStart = new BigInteger("0");
    for (int i = 0; i < numShards; i++) {
        Shard shard = new Shard();
        shard.setShardId(shardIdPrefix + i);
        shard.setSequenceNumberRange(sequenceNumberRange);
        BigInteger hashKeyRangeEnd = hashKeyRangeStart.add(perShardHashKeyRange);
        HashKeyRange hashKeyRange = new HashKeyRange();
        hashKeyRange.setStartingHashKey(hashKeyRangeStart.toString());
        hashKeyRange.setEndingHashKey(hashKeyRangeEnd.toString());
        shards.add(shard);
    }

    return shards;
}

From source file:com.og.elliptic.sdk.main.java

private static void elGamalString(WeierStrassCurve curve) {
    // Droulement de El Gamal
    // Cryptage/*  ww w. j a va2 s  .  c  o  m*/
    PointGMP generateur = new PointGMP(curve.getGx(), curve.getGy(), curve);// le point gnrateur qui servira  calculer notre clef
    // secrte
    Random rnd = new Random();

    BigInteger clefSecrete = BigInteger.probablePrime(7, rnd);
    PointGMP publicKey = generateur.mult(clefSecrete);// on calcule notre clef secrte, qui nous servira  crypter les messages (h)

    BigInteger m = new BigInteger(Base64.decodeBase64("bonjour lesil"));

    BigInteger k = BigInteger.probablePrime(7, rnd);// on choisit un k random

    PointGMP C1 = generateur.mult(k);// on multiplie le gnrateur par k
    PointGMP tmp = publicKey.mult(k);
    BigInteger C2 = m.add(tmp.getX());// on multiplie notre clef secrte par k

    // Dcryptage
    PointGMP temp = C1.mult(clefSecrete);// on multiplie C1 par notre clef secrte
    BigInteger messageTraduit = C2.subtract(temp.getX());// et on obtient le message en ajoutant m2 avec l'oppos de temp
    messageTraduit = messageTraduit.mod(curve.getP());

    if (m == messageTraduit)
        System.out.println("El Gamal fonctionnel");
    else
        System.out.println("El Gamal non fonctionnel");

    System.out.println("Message a retrouver " + m + " " + Base64.encodeBase64String(m.toByteArray()) + "\n");
    System.out.println("Resultat El gamal " + messageTraduit + " "
            + Base64.encodeBase64String(messageTraduit.toByteArray()) + "\n");

}

From source file:main.java.utils.Utility.java

public static String asUnsignedDecimalString(long l) {
    /** the constant 2^64 */
    BigInteger TWO_64 = BigInteger.ONE.shiftLeft(64);
    BigInteger b = BigInteger.valueOf(l);

    if (b.signum() < 0) {
        b = b.add(TWO_64);
    }/*from   w w  w.  jav  a2  s.c o m*/

    return b.toString();
}