Example usage for java.math BigInteger signum

List of usage examples for java.math BigInteger signum

Introduction

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

Prototype

int signum

To view the source code for java.math BigInteger signum.

Click Source Link

Document

The signum of this BigInteger: -1 for negative, 0 for zero, or 1 for positive.

Usage

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 w  w .ja  v  a 2 s.  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

/**
 * Computes the Window NAF (non-adjacent Form) of an integer.
 * @param width The width <code>w</code> of the Window NAF. The width is
 * defined as the minimal number <code>w</code>, such that for any
 * <code>w</code> consecutive digits in the resulting representation, at
 * most one is non-zero./*from w ww. j a  v  a 2s .c  om*/
 * @param k The integer of which the Window NAF is computed.
 * @return The Window NAF of the given width, such that the following holds:
 * <code>k = &sum;<sub>i=0</sub><sup>l-1</sup> k<sub>i</sub>2<sup>i</sup>
 * </code>, where the <code>k<sub>i</sub></code> denote the elements of the
 * returned <code>byte[]</code>.
 */
public static byte[] generateWindowNaf(int width, BigInteger k) {
    if (width == 2) {
        return generateNaf(k);
    }

    if (width < 2 || width > 8) {
        throw new IllegalArgumentException("'width' must be in the range [2, 8]");
    }
    if (k.signum() == 0) {
        return EMPTY_BYTES;
    }

    byte[] wnaf = new byte[k.bitLength() + 1];

    // 2^width and a mask and sign bit set accordingly
    int pow2 = 1 << width;
    int mask = pow2 - 1;
    int sign = pow2 >>> 1;

    boolean carry = false;
    int length = 0, pos = 0;

    while (pos <= k.bitLength()) {
        if (k.testBit(pos) == carry) {
            ++pos;
            continue;
        }

        k = k.shiftRight(pos);

        int digit = k.intValue() & mask;
        if (carry) {
            ++digit;
        }

        carry = (digit & sign) != 0;
        if (carry) {
            digit -= pow2;
        }

        length += (length > 0) ? pos - 1 : pos;
        wnaf[length++] = (byte) digit;
        pos = width;
    }

    // Reduce the WNAF array to its actual length
    if (wnaf.length > length) {
        wnaf = trim(wnaf, length);
    }

    return wnaf;
}

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 .  j ava 2 s.  com*/
    }

    return b.toString();
}

From source file:ja.ohac.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/* ww w.j  a  va2  s . c o  m*/

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final BigInteger rate = GenericUtils.parseCoin(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, rate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.aegiswallet.utils.BasicUtils.java

public static BigInteger toNanoCoins(final String value, final int shift) {

    try {//from  w w  w.  ja va 2s . c  o  m
        final BigInteger nanoCoins = new BigDecimal(value).movePointRight(8 - shift).toBigIntegerExact();

        if (nanoCoins.signum() < 0)
            throw new IllegalArgumentException("negative amount: " + value);
        if (nanoCoins.compareTo(NetworkParameters.MAX_MONEY) > 0)
            Log.e(TAG, "AMOUNT TOO LARGE");

        return nanoCoins;
    } catch (ArithmeticException e) {
        Log.d(TAG, e.getMessage());
        return BigInteger.ZERO;
    }
}

From source file:Main.java

public static int[] generateCompactWindowNaf(int width, BigInteger k) {
    if (width == 2) {
        return generateCompactNaf(k);
    }/* ww w .j av a  2 s . co  m*/

    if (width < 2 || width > 16) {
        throw new IllegalArgumentException("'width' must be in the range [2, 16]");
    }
    if ((k.bitLength() >>> 16) != 0) {
        throw new IllegalArgumentException("'k' must have bitlength < 2^16");
    }
    if (k.signum() == 0) {
        return EMPTY_INTS;
    }

    int[] wnaf = new int[k.bitLength() / width + 1];

    // 2^width and a mask and sign bit set accordingly
    int pow2 = 1 << width;
    int mask = pow2 - 1;
    int sign = pow2 >>> 1;

    boolean carry = false;
    int length = 0, pos = 0;

    while (pos <= k.bitLength()) {
        if (k.testBit(pos) == carry) {
            ++pos;
            continue;
        }

        k = k.shiftRight(pos);

        int digit = k.intValue() & mask;
        if (carry) {
            ++digit;
        }

        carry = (digit & sign) != 0;
        if (carry) {
            digit -= pow2;
        }

        int zeroes = length > 0 ? pos - 1 : pos;
        wnaf[length++] = (digit << 16) | zeroes;
        pos = width;
    }

    // Reduce the WNAF array to its actual length
    if (wnaf.length > length) {
        wnaf = trim(wnaf, length);
    }

    return wnaf;
}

From source file:org.objectspace.rfid.elatec.ElatecRFID.java

public static String longToHex(long l) {
    BigInteger b = BigInteger.valueOf(l);
    if (b.signum() < 0)
        b = b.add(TWO_64);//w w  w . jav  a2s. c om
    String str = b.toString(16);
    if (str.length() == 16)
        str = str.substring(8);
    while (str.length() < 8)
        str = "0" + str;
    return str;
}

From source file:org.objectspace.rfid.elatec.ElatecRFID.java

public static String intToHex(int i) {
    BigInteger b = BigInteger.valueOf(i);
    if (b.signum() < 0)
        b = b.add(TWO_64);/*from w  w w . j a v  a  2  s  .c  o  m*/
    String str = b.toString(16);
    if (str.length() == 16)
        str = str.substring(12);
    while (str.length() < 4)
        str = "0" + str;
    return str;
}

From source file:Util.java

public static BigInteger bitwiseGcd(BigInteger u, BigInteger v) {
    if (u.equals(BigInteger.ZERO))
        return v;
    if (v.equals(BigInteger.ZERO))
        return u;

    //      System.out.format("u=%s=%s\nu.getLowestSetBit()=%s\n%s>>%s=%s = %s\n", u, u.toString(2), u.getLowestSetBit(), u, u.getLowestSetBit(), u.shiftRight(u.getLowestSetBit()), u.shiftRight(u.getLowestSetBit()).toString(2));

    int uBit = u.getLowestSetBit();
    int vBit = v.getLowestSetBit();
    int k = (uBit <= vBit ? uBit : vBit);

    while (u.signum() > 0) {
        // first ensure that both are odd
        u = u.shiftRight(u.getLowestSetBit());
        v = v.shiftRight(v.getLowestSetBit());
        if (u.subtract(v).signum() >= 0) {
            u = (u.subtract(v)).shiftRight(1);
        } else {/*w  ww .  ja  va 2  s  .  co m*/
            v = (v.subtract(u)).shiftRight(1);
        }
    }

    return v.shiftLeft(k);
}

From source file:com.dopecoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float leafBtcConversion,
        final String userAgent, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//  w ww .j a v  a 2  s  .c  o m

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger leafRate = btcRate.multiply(BigDecimal.valueOf(leafBtcConversion))
                                        .toBigInteger();

                                if (leafRate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, leafRate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}