Example usage for java.math BigInteger bitLength

List of usage examples for java.math BigInteger bitLength

Introduction

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

Prototype

public int bitLength() 

Source Link

Document

Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.

Usage

From source file:org.esa.cci.sst.tool.Configuration.java

private long parsePattern(String key, String value) {
    final long pattern;
    try {/*from   w  ww.ja v  a2s  .  c  o  m*/
        final BigInteger bigInteger = new BigInteger(value, 16);
        if (bigInteger.bitLength() > 64) {
            throw new ToolException("Too many bits in pattern: " + key, ToolException.TOOL_CONFIGURATION_ERROR);
        }
        if (bigInteger.bitCount() > 1) {
            throw new ToolException("Too many bits set in pattern: " + key,
                    ToolException.TOOL_CONFIGURATION_ERROR);
        }
        pattern = bigInteger.longValue();
    } catch (NumberFormatException e) {
        throw new ToolException("Cannot parse pattern: " + key, e, ToolException.TOOL_CONFIGURATION_ERROR);
    }
    return pattern;
}

From source file:com.dulion.astatium.mesh.shredder.ContextManager.java

private void logTree() {
    String space = Strings.repeat("  ", 40);

    Context[] array = new Context[contextMap.size()];
    contextMap.values().toArray(array);/*from  ww w.  j  a  v a2s . c  om*/
    sort(array, Context.byContext());

    int maxSize = 0;
    for (Context context : array) {
        Location location = context.getRange().getLower();
        BigInteger numerator = ((RationalLocation) location).getNumerator();

        String num = Base64.getEncoder().encodeToString(numerator.toByteArray());
        int numSize = numerator.bitLength() / 8 + 1;
        if (numSize > maxSize) {
            maxSize = numSize;
        }

        BigInteger denominator = ((RationalLocation) location).getDenominator();
        String den = Base64.getEncoder().encodeToString(denominator.toByteArray());
        int denSize = denominator.bitLength() / 8 + 1;
        if (denSize > maxSize) {
            maxSize = denSize;
        }

        int depth = context.getDepth() - 1;
        String indent = space.substring(0, depth << 1);
        LOG.info(String.format("[%15s|%15s]%s", num, den, indent + context.getName()));
    }

    LOG.info("Max byte size: {}", maxSize);
}

From source file:com.acmemotors.obd2.OBD2Controller.java

public List<String> decodePidsSupported(String response, int offset) {
    List<String> pids = new ArrayList<>();

    String[] respsonseLines = response.split("\n");

    StringBuilder pidString = new StringBuilder();

    String[] elements = respsonseLines[1].split(" ");

    for (int j = 7; j < elements.length; j++) {
        pidString.append(elements[j]);/*from   w w  w  . ja  va 2  s  . com*/
    }

    BigInteger bigInt = new BigInteger(pidString.toString(), 16);

    int j = 0;
    for (int i = bigInt.bitLength() - 1; i >= 0; i--) {
        int pidId = j + offset + 1;

        if (bigInt.testBit(i)) {
            pids.add(Integer.toHexString(pidId));
        }

        j++;
    }

    return pids;
}

From source file:com.amazon.carbonado.repo.jdbc.LoggingPreparedStatement.java

private void logStatement() {
    String statement = mSQL;// ww w . ja  va2 s . co  m

    Object[] params;
    BigInteger setParams;
    if ((params = mParams) != null && (setParams = mSetParams) != BigInteger.ZERO) {
        int length = setParams.bitLength();
        StringBuilder b = new StringBuilder(statement.length() + length * 10);
        b.append(statement);
        b.append(" -- ");
        boolean any = false;
        for (int i = 0; i < length; i++) {
            if (setParams.testBit(i)) {
                if (any) {
                    b.append(", [");
                } else {
                    b.append('[');
                    any = true;
                }
                b.append(i);
                b.append("]=");
                b.append(params[i]);
            }
        }
        statement = b.toString();
    }

    mLog.debug(statement);
}

From source file:com.cloud.utils.net.NetUtils.java

public static String getIp6FromRange(final String ip6Range) {
    final String[] ips = ip6Range.split("-");
    final String startIp = ips[0];
    final IPv6Address start = IPv6Address.fromString(startIp);
    final BigInteger gap = countIp6InRange(ip6Range);
    BigInteger next = new BigInteger(gap.bitLength(), s_rand);
    while (next.compareTo(gap) >= 0) {
        next = new BigInteger(gap.bitLength(), s_rand);
    }//from  w  w w  .  j a v  a2s  . c o m
    InetAddress resultAddr = null;
    final BigInteger startInt = convertIPv6AddressToBigInteger(start);
    if (startInt != null) {
        final BigInteger resultInt = startInt.add(next);
        try {
            resultAddr = InetAddress.getByAddress(resultInt.toByteArray());
        } catch (final UnknownHostException e) {
            return null;
        }
    }
    if (resultAddr != null) {
        final IPv6Address ip = IPv6Address.fromInetAddress(resultAddr);
        return ip.toString();
    }
    return null;
}

From source file:com.google.uzaygezen.core.LongBitVector.java

@Override
public void copyFrom(BigInteger s) {
    Preconditions.checkArgument(s.signum() >= 0, s);
    Preconditions.checkArgument(s.bitLength() <= size());
    // Note that the long value will be negative iff bitLength == 644 and bit 63
    // is set./*from   w ww.  j a  v a2 s.  c om*/
    copyFrom(s.longValue());
}

From source file:org.sputnikdev.bluetooth.gattparser.FieldHolder.java

/**
 * Sets the field value from the given enumeration (enumeration key).
 * @param value a new field value/*from w  w w. jav  a2s .co m*/
 */
public void setEnumeration(Enumeration value) {
    if (value == null) {
        this.value = null;
    } else {

        BigInteger key = value.getKey();

        if (field.getFormat().isStruct()) {
            this.value = new TwosComplementNumberFormatter().serialize(key, key.bitLength(), false)
                    .toByteArray();
        } else if (field.getFormat().isString()) {
            String encoding = field.getFormat().getType() == FieldType.UTF8S ? "UTF-8" : "UTF-16";
            try {
                this.value = new String(new TwosComplementNumberFormatter()
                        .serialize(key, key.bitLength(), false).toByteArray(), encoding);
            } catch (UnsupportedEncodingException e) {
                throw new IllegalStateException(e);
            }
        } else {
            setBigInteger(key);
        }
    }
}

From source file:de.undercouch.bson4jackson.BsonGenerator.java

@Override
public void writeNumber(BigInteger v) throws IOException, JsonGenerationException {
    int bl = v.bitLength();
    if (bl < 32) {
        writeNumber(v.intValue());//from w  ww.  j  a va2  s .  co  m
    } else if (bl < 64) {
        writeNumber(v.longValue());
    } else {
        writeString(v.toString());
    }
}

From source file:org.sputnikdev.bluetooth.gattparser.FieldHolder.java

/**
 * Sets the field value into a new BigInteger value.
 * @param value a new field value//from  w  w  w .j a v a 2 s  .  c  o  m
 */
public void setBigInteger(BigInteger value) {
    if (value == null) {
        this.value = null;
    } else {
        BigDecimal vl = new BigDecimal(value);
        Double maximum = field.getMaximum();
        if (maximum != null && vl.compareTo(new BigDecimal(maximum)) > 0) {
            throw new IllegalArgumentException("Value [" + value + "] is greater than maximum: " + maximum);
        }
        Double minimum = field.getMinimum();
        if (minimum != null && vl.compareTo(new BigDecimal(minimum)) < 0) {
            throw new IllegalArgumentException("Value [" + value + "] is less than minimum: " + minimum);
        }
        double multiplier = getMultiplier();
        double offset = getOffset();
        BigInteger adjusted;
        if (multiplier != 1.0 || offset != 0.0) {
            adjusted = vl.subtract(BigDecimal.valueOf(offset)).setScale(0, RoundingMode.HALF_UP)
                    .divide(BigDecimal.valueOf(multiplier)).toBigInteger();
        } else {
            adjusted = value;
        }

        if (field.getFormat().isStruct()) {
            this.value = new TwosComplementNumberFormatter().serialize(adjusted, adjusted.bitLength(), false)
                    .toByteArray();
        } else {
            this.value = getConverter().convert(null, adjusted);
        }
    }
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}//from  w w w .j av a  2s.com
 */
@Override
public final int initRsaPrivateKey(final ByteArray primeP, final ByteArray primeQ,
        final ByteArray primeExponentP, final ByteArray primeExponentQ, final ByteArray crtCoefficient)
        throws McbpCryptoException {
    try {
        final BigInteger p = new BigInteger(primeP.toHexString(), 16);
        final BigInteger q = new BigInteger(primeQ.toHexString(), 16);
        final BigInteger dp = new BigInteger(primeExponentP.toHexString(), 16);
        final BigInteger dq = new BigInteger(primeExponentQ.toHexString(), 16);
        final BigInteger a = new BigInteger(crtCoefficient.toHexString(), 16);

        final BigInteger n = p.multiply(q);
        final BigInteger e = dp.modInverse(p.subtract(BigInteger.ONE));

        final BigInteger d = e.modInverse(p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE))
                .divide((p.subtract(BigInteger.ONE)).gcd(q.subtract(BigInteger.ONE))));

        final RSAPrivateKey rsaKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new RSAPrivateCrtKeySpec(n, e, d, p, q, dp, dq, a));

        initRsaPrivate(rsaKey);

        return n.bitLength() / 8;

    } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new McbpCryptoException(e.toString());
    }
}