Example usage for java.math BigInteger subtract

List of usage examples for java.math BigInteger subtract

Introduction

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

Prototype

public BigInteger subtract(BigInteger val) 

Source Link

Document

Returns a BigInteger whose value is (this - val) .

Usage

From source file:localSPs.CubbyAPI.java

public double getStorageSize() throws IOException {
    BigInteger num = new BigInteger("1024");
    String ans = "";
    BigInteger totalMemory = new BigInteger("5368709120");
    BigInteger used;/*w w w .ja  v  a2 s .  co  m*/
    File dir = new File(ROOT_PATH);
    long totalUsed = 0; // total bytes
    List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
    for (File file : files) {
        totalUsed += file.length();
    }
    used = new BigInteger(String.valueOf(totalUsed));
    ans = totalMemory.subtract(used).divide(num).divide(num).toString();//MB
    return (Double.parseDouble(ans));
}

From source file:uk.co.petertribble.jangle.SnmpChart.java

/**
 * Update the oids.//from   w ww .j av  a2s  . co m
 */
public void updateAccessory() {
    double value;
    long newsnap = (new Date()).getTime();
    // loop over all oids
    for (String stat : tsmap.keySet()) {
        try {
            BigInteger newvalue = sc.getValue(stat).getNumber();
            if (showdelta) {
                BigInteger bd = newvalue.subtract(valueMap.get(stat));
                double dt = (double) (newsnap - lastsnap);
                value = 1000.0 * (bd.doubleValue() / dt);
                valueMap.put(stat, newvalue);
            } else {
                value = newvalue.doubleValue();
            }
            tsmap.get(stat).add(new Millisecond(), value);
        } catch (SnmpException sne) {
        }
    }
    lastsnap = newsnap;
    fireTableDataChanged();
}

From source file:com.chinamobile.bcbsp.util.Bytes.java

/**
 * Split passed range. Expensive operation relatively. Uses BigInteger math.
 * Useful splitting ranges for MapReduce jobs.
 *
 * @param a/*w  w w  .  j ava2  s.c  o m*/
 *        Beginning of range
 * @param b
 *        End of range
 * @param num
 *        Number of times to split range. Pass 1 if you want to split the
 *        range in two; i.e. one split.
 * @return Array of dividing values
 */
public static byte[][] split(final byte[] a, final byte[] b, final int num) {
    byte[] aPadded;
    byte[] bPadded;
    if (a.length < b.length) {
        aPadded = padTail(a, b.length - a.length);
        bPadded = b;
    } else if (b.length < a.length) {
        aPadded = a;
        bPadded = padTail(b, a.length - b.length);
    } else {
        aPadded = a;
        bPadded = b;
    }
    if (compareTo(aPadded, bPadded) >= 0) {
        throw new IllegalArgumentException("b <= a");
    }
    if (num <= 0) {
        throw new IllegalArgumentException("num cannot be < 0");
    }
    byte[] prependHeader = { 1, 0 };
    BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
    BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
    BigInteger diffBI = stopBI.subtract(startBI);
    BigInteger splitsBI = BigInteger.valueOf(num + 1);
    if (diffBI.compareTo(splitsBI) < 0) {
        return null;
    }
    BigInteger intervalBI;
    try {
        intervalBI = diffBI.divide(splitsBI);
    } catch (Exception e) {
        LOG.error("Exception caught during division", e);
        return null;
    }
    byte[][] result = new byte[num + 2][];
    result[0] = a;
    for (int i = 1; i <= num; i++) {
        BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
        byte[] padded = curBI.toByteArray();
        if (padded[1] == 0) {
            padded = tail(padded, padded.length - 2);
        } else {
            padded = tail(padded, padded.length - 1);
        }
        result[i] = padded;
    }
    result[num + 1] = b;
    return result;
}

From source file:localSPs.SpiderOakAPI.java

public double getStorageSize() throws IOException {
    BigInteger num = new BigInteger("1024");
    String ans = "";
    BigInteger totalMemory = new BigInteger("32212254720");
    BigInteger used;/*from  w ww . j a va2s .  c om*/
    File dir = new File(ROOT_PATH);
    long totalUsed = 0; // total bytes

    List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
    for (File file : files) {
        totalUsed += file.length();
    }
    used = new BigInteger(String.valueOf(totalUsed));
    ans = totalMemory.subtract(used).divide(num).divide(num).toString();//MB
    return (Double.parseDouble(ans));
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private BigInteger step3ComputeLowerBound(final BigInteger s, final BigInteger modulus,
        final BigInteger lowerIntervalBound) {
    BigInteger lowerBound = lowerIntervalBound.multiply(s);
    lowerBound = lowerBound.subtract(BigInteger.valueOf(3).multiply(this.bigB));
    lowerBound = lowerBound.add(BigInteger.ONE);
    lowerBound = lowerBound.divide(modulus);

    return lowerBound;
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private BigInteger step3ComputeUpperBound(final BigInteger s, final BigInteger modulus,
        final BigInteger upperIntervalBound) {
    BigInteger upperBound = upperIntervalBound.multiply(s);
    upperBound = upperBound.subtract(BigInteger.valueOf(2).multiply(bigB));
    // ceil/*  w  w w .j  a  v  a2s  . c om*/
    BigInteger[] tmp = upperBound.divideAndRemainder(modulus);
    if (BigInteger.ZERO.compareTo(tmp[1]) != 0) {
        upperBound = BigInteger.ONE.add(tmp[0]);
    } else {
        upperBound = tmp[0];
    }

    return upperBound;
}

From source file:org.multibit.utils.CSMiscUtils.java

public static String getDescriptionOfTransactionAssetChanges(Wallet wallet, Transaction tx) {
    if (wallet == null || tx == null)
        return "";

    Map<Integer, BigInteger> receiveMap = wallet.CS.getAssetsSentToMe(tx);
    Map<Integer, BigInteger> sendMap = wallet.CS.getAssetsSentFromMe(tx);

    //   System.out.println(">>>> tx = " + tx.getHashAsString());
    //   System.out.println(">>>>     receive map = " +  receiveMap);
    //   System.out.println(">>>>     send map = " +  sendMap);

    //Map<String, String> nameAmountMap = new TreeMap<>();
    ArrayList<String> nameAmounts = new ArrayList<>();

    boolean isSentByMe = tx.sent(wallet);
    Map<Integer, BigInteger> loopMap = (isSentByMe) ? sendMap : receiveMap;

    //   Integer assetID = null;
    BigInteger netAmount = null;

    //   for (Map.Entry<Integer, BigInteger> entry : loopMap.entrySet()) {
    for (Integer assetID : loopMap.keySet()) {
        //       assetID = entry.getKey();
        if (assetID == null || assetID == 0)
            continue; // skip bitcoin

        BigInteger receivedAmount = receiveMap.get(assetID); // should be number of raw units
        BigInteger sentAmount = sendMap.get(assetID);
        boolean isReceivedAmountMissing = (receivedAmount == null);
        boolean isSentAmountMissing = (sentAmount == null);

        netAmount = BigInteger.ZERO;
        if (!isReceivedAmountMissing)
            netAmount = netAmount.add(receivedAmount);
        if (!isSentAmountMissing)
            netAmount = netAmount.subtract(sentAmount);

        if (isSentByMe && !isSentAmountMissing && sentAmount.equals(BigInteger.ZERO)) {
            // Catch a case where for a send transaction, the send amount for an asset is 0,
            // but the receive cmount is not 0.  Also the asset was not valid.
            continue;
        }/*from  ww  w .  j a v a2s  . co m*/

        CSAsset asset = wallet.CS.getAsset(assetID);
        if (asset == null) {
            // something went wrong, we have asset id but no asset, probably deleted.
            // For now, we carry on, and we display what we know.
        }

        if (netAmount.equals(BigInteger.ZERO) && isSentByMe) {
            // If net asset is 0 and this is our send transaction,
            // we don't need to show anything, as this probably due to implicit transfer.
            // So continue the loop.
            continue;
        }

        if (netAmount.equals(BigInteger.ZERO) && !isSentByMe) {
            // Receiving an asset, where the value is 0 because its not confirmed yet,
            // or not known because asset files not uploaded so we dont know display format.
            // Anyway, we don't do anything here as we do want to display this incoming
            // transaction the best we can.
        }

        //       System.out.println(">>>>     isSentAmountMissing = " + isSentAmountMissing);
        //       System.out.println(">>>>     asset reference = " + asset.getAssetReference());
        //       System.out.println(">>>>     asset name = " + asset.getName());

        String name = null;
        CoinSparkGenesis genesis = null;
        boolean isUnknown = false;
        if (asset != null) {
            genesis = asset.getGenesis();
            name = asset.getNameShort(); // could return null?
        }
        if (name == null) {
            isUnknown = true;
            if (genesis != null) {
                name = "Asset from " + genesis.getDomainName();
            } else {
                // No genesis block found yet
                name = "Other Asset";
            }
        }

        String s1 = null;
        if (asset == null || isUnknown == true || (netAmount.equals(BigInteger.ZERO) && !isSentByMe)) {
            // We don't have formatting details since asset is unknown or deleted
            // If there is a quantity, we don't display it since we don't have display format info
            // Of if incoming asset transfer, unconfirmed, it will be zero, so show ... instead
            s1 = "...";
        } else {
            BigDecimal displayUnits = getDisplayUnitsForRawUnits(asset, netAmount);
            s1 = CSMiscUtils.getFormattedDisplayString(asset, displayUnits);
        }
        String s2 = name + ": " + s1;
        nameAmounts.add(s2);
        //break; // TODO: return the first asset we find, in future return map<Integer,BigInteger>
    }

    if (!nameAmounts.isEmpty()) {
        Collections.sort(nameAmounts);
    }
    BigInteger satoshiAmount = receiveMap.get(0);
    satoshiAmount = satoshiAmount.subtract(sendMap.get(0));
    String btcAmount = Utils.bitcoinValueToFriendlyString(satoshiAmount);
    nameAmounts.add("BTC: " + btcAmount);

    String result = StringUtils.join(nameAmounts, ", ");

    //   System.out.println(">>>>     result = " +  result);

    return result;
}

From source file:net.ripe.ipresource.IpRange.java

public List<IpRange> splitToPrefixes() {
    BigInteger rangeEnd = getEnd().getValue();
    BigInteger currentRangeStart = getStart().getValue();
    int startingPrefixLength = getType().getBitSize();
    List<IpRange> prefixes = new LinkedList<IpRange>();

    while (currentRangeStart.compareTo(rangeEnd) <= 0) {
        int maximumPrefixLength = getMaximumLengthOfPrefixStartingAtIpAddressValue(currentRangeStart,
                startingPrefixLength);/*ww w.j  ava 2  s  .  co  m*/
        BigInteger maximumSizeOfPrefix = rangeEnd.subtract(currentRangeStart).add(BigInteger.ONE);
        BigInteger currentSizeOfPrefix = BigInteger.valueOf(2).pow(maximumPrefixLength);

        while ((currentSizeOfPrefix.compareTo(maximumSizeOfPrefix) > 0) && (maximumPrefixLength > 0)) {
            maximumPrefixLength--;
            currentSizeOfPrefix = BigInteger.valueOf(2).pow(maximumPrefixLength);
        }

        BigInteger currentRangeEnd = currentRangeStart
                .add(BigInteger.valueOf(2).pow(maximumPrefixLength).subtract(BigInteger.ONE));
        IpRange prefix = (IpRange) IpResourceRange.assemble(currentRangeStart, currentRangeEnd, getType());

        prefixes.add(prefix);

        currentRangeStart = currentRangeEnd.add(BigInteger.ONE);
    }

    return prefixes;
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private void stepTwoC() throws Exception {
    byte[] send;//from  w w w .  j  av a 2 s .  com
    IHttpRequestResponse response;
    byte[] request;

    BigInteger n = this.pubKey.getModulus();

    loggerInstance.log(getClass(), "Step 2c: Searching with one interval left", Logger.LogLevel.INFO);

    // initial ri computation - ri = 2(b*(si-1)-2*B)/n
    BigInteger ri = this.si.multiply(this.m[0].upper);
    ri = ri.subtract(BigInteger.valueOf(2).multiply(this.bigB));
    ri = ri.multiply(BigInteger.valueOf(2));
    ri = ri.divide(n);

    // initial si computation
    BigInteger upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower);
    BigInteger lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper);

    // to counter .add operation in do while
    this.si = lowerBound.subtract(BigInteger.ONE);

    do {
        // Check if user has cancelled the worker
        if (isCancelled()) {
            loggerInstance.log(getClass(), "Decryption Attack Executor Worker cancelled by user",
                    Logger.LogLevel.INFO);
            return;
        }

        this.si = this.si.add(BigInteger.ONE);
        // lowerBound <= si < upperBound
        if (this.si.compareTo(upperBound) > 0) {
            // new values
            ri = ri.add(BigInteger.ONE);
            upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower);
            lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper);
            this.si = lowerBound;
        }
        send = prepareMsg(this.c0, this.si);

        request = this.requestResponse.getRequest();
        String[] components = Decoder.getComponents(this.parameter.getJoseValue());
        components[1] = Decoder.base64UrlEncode(send);

        String newComponentsConcatenated = Decoder.concatComponents(components);

        request = JoseParameter.updateRequest(request, this.parameter, helpers, newComponentsConcatenated);

        response = callbacks.makeHttpRequest(this.httpService, request);
        updateAmountRequest();

    } while (oracle.getResult(response.getResponse()) != BleichenbacherPkcs1Oracle.Result.VALID);
    loggerInstance.log(getClass(), "Matching response: " + helpers.bytesToString(response.getResponse()),
            Logger.LogLevel.DEBUG);
}

From source file:com.ethercamp.harmony.service.WalletService.java

public WalletInfoDTO getWalletInfo() {
    BigInteger gasPrice = BigInteger.valueOf(ethereum.getGasPrice());
    BigInteger txFee = gasLimit.multiply(gasPrice);

    List<WalletAddressDTO> list = addresses.entrySet().stream().flatMap(e -> {
        final String hexAddress = e.getKey();
        try {//w w  w  .  j  ava  2 s. co  m
            final byte[] address = Hex.decode(hexAddress);
            final BigInteger balance = repository.getBalance(address);
            final BigInteger sendBalance = calculatePendingChange(pendingSendTransactions, hexAddress, txFee);
            final BigInteger receiveBalance = calculatePendingChange(pendingReceiveTransactions, hexAddress,
                    BigInteger.ZERO);

            return Stream.of(new WalletAddressDTO(e.getValue(), e.getKey(), balance,
                    receiveBalance.subtract(sendBalance), keystore.hasStoredKey(e.getKey())));
        } catch (Exception exception) {
            log.error("Error in making wallet address " + hexAddress, exception);
            return Stream.empty();
        }
    }).collect(Collectors.toList());

    BigInteger totalAmount = list.stream().map(t -> t.getAmount()).reduce(BigInteger.ZERO,
            (state, amount) -> state.add(amount));

    WalletInfoDTO result = new WalletInfoDTO(totalAmount);

    result.getAddresses().addAll(list);
    return result;
}