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:Base64.java

/**
 * Returns a byte-array representation of a <code>BigInteger</code> without sign bit.
 *
 * @param bigInt <code>BigInteger</code> to be converted
 * @return a byte array representation of the BigInteger parameter
 *//*from ww w. j av a2  s .  c  o  m*/
static byte[] toIntegerBytes(BigInteger bigInt) {
    int bitlen = bigInt.bitLength();
    // round bitlen
    bitlen = ((bitlen + 7) >> 3) << 3;
    byte[] bigBytes = bigInt.toByteArray();

    if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
        return bigBytes;
    }
    // set up params for copying everything but sign bit
    int startSrc = 0;
    int len = bigBytes.length;

    // if bigInt is exactly byte-aligned, just skip signbit in copy
    if ((bigInt.bitLength() % 8) == 0) {
        startSrc = 1;
        len--;
    }
    int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
    byte[] resizedBytes = new byte[bitlen / 8];
    System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
    return resizedBytes;
}

From source file:net.sf.jasperreports.data.cache.BigIntegerStore.java

@Override
public ColumnValues createValues() {
    int count = rawStore.count();
    if (count == 0) {
        // no values
        if (log.isDebugEnabled()) {
            log.debug(this + ": empty values");
        }//from  ww  w .ja  va2 s  . c  om

        return EmptyColumnValues.instance();
    }

    if (min.equals(max)) {
        // constant value
        if (log.isDebugEnabled()) {
            log.debug(this + ": constant values of size " + count);
        }

        return new ConstantColumnValue(count, min);
    }

    BigInteger delta = max.subtract(min);
    int deltaLength = delta.bitLength();
    boolean useOffset = false;
    ColumnValues primitiveValues = null;
    if (deltaLength < 64)// bitLength() excludes the sign
    {
        // if all values can be stored as long, do not use a BigInteger offset
        useOffset = !(min.signum() >= 0 && min.bitLength() < 64 && max.signum() >= 0 && max.bitLength() < 64);

        if (log.isDebugEnabled()) {
            log.debug(this + ": creating privitive store of size " + count + ", with offset " + useOffset);
        }

        primitiveValues = createPrimitiveValues(useOffset);
    }

    ColumnValues columnValues;
    if (primitiveValues == null) {
        if (log.isDebugEnabled()) {
            log.debug(this + ": creating raw array store of size " + count);
        }

        return rawStore.createValues();
    } else {
        ValueTransformer transformer = useOffset ? new NumberToBigIntegerOffsetTransformer(min)
                : NumberToBigIntegerTransformer.instance();
        columnValues = new TransformedColumnValues(primitiveValues, transformer);
    }
    return columnValues;
}

From source file:org.polymap.core.runtime.recordstore.lucene.NumericValueCoder.java

public boolean encode(Document doc, String key, Object value, boolean indexed, boolean stored) {
    if (value instanceof Number) {
        NumericField field = (NumericField) doc.getFieldable(key);
        if (field == null) {
            field = new NumericField(key, stored ? Store.YES : Store.NO, indexed);
            doc.add(field);/*from  w  w w.j a  va2s  . co m*/
        }
        if (value instanceof Integer) {
            field.setIntValue((Integer) value);
        } else if (value instanceof Long) {
            field.setLongValue((Long) value);
        } else if (value instanceof Float) {
            field.setFloatValue((Float) value);
        } else if (value instanceof Double) {
            field.setDoubleValue((Double) value);
        } else if (value instanceof BigInteger) {
            BigInteger bint = (BigInteger) value;
            if (bint.bitLength() < 32) {
                field.setIntValue(bint.intValue());
            } else if (bint.bitLength() < 64) {
                field.setLongValue(bint.longValue());
            } else {
                throw new RuntimeException("Too much bits in BigInteger: " + bint.bitLength());
            }
        } else if (value instanceof BigDecimal) {
            BigDecimal bdeci = (BigDecimal) value;
            // FIXME check double overflow
            field.setDoubleValue(bdeci.doubleValue());
        } else {
            throw new RuntimeException("Unknown Number type: " + value.getClass());
        }
        //log.debug( "encode(): " + field );
        return true;
    } else {
        return false;
    }
}

From source file:com.rabbitmq.client.impl.ValueWriter.java

public final void writeFieldValue(Object value) throws IOException {
    if (value instanceof String) {
        writeOctet('S');
        writeLongstr((String) value);
    } else if (value instanceof LongString) {
        writeOctet('S');
        writeLongstr((LongString) value);
    } else if (value instanceof Integer) {
        writeOctet('I');
        writeLong((Integer) value);
    } else if (value instanceof BigDecimal) {
        writeOctet('D');
        BigDecimal decimal = (BigDecimal) value;
        writeOctet(decimal.scale());/*  w w w  .j  av  a 2  s. c  o m*/
        BigInteger unscaled = decimal.unscaledValue();
        if (unscaled.bitLength() > 32) /*Integer.SIZE in Java 1.5*/
            throw new IllegalArgumentException("BigDecimal too large to be encoded");
        writeLong(decimal.unscaledValue().intValue());
    } else if (value instanceof Date) {
        writeOctet('T');
        writeTimestamp((Date) value);
    } else if (value instanceof Map) {
        writeOctet('F');
        // Ignore the warnings here.  We hate erasure
        // (not even a little respect)
        // (We even have trouble recognising it.)
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) value;
        writeTable(map);
    } else if (value instanceof Byte) {
        writeOctet('b');
        out.writeByte((Byte) value);
    } else if (value instanceof Double) {
        writeOctet('d');
        out.writeDouble((Double) value);
    } else if (value instanceof Float) {
        writeOctet('f');
        out.writeFloat((Float) value);
    } else if (value instanceof Long) {
        writeOctet('l');
        out.writeLong((Long) value);
    } else if (value instanceof Short) {
        writeOctet('s');
        out.writeShort((Short) value);
    } else if (value instanceof Boolean) {
        writeOctet('t');
        out.writeBoolean((Boolean) value);
    } else if (value instanceof byte[]) {
        writeOctet('x');
        writeLong(((byte[]) value).length);
        out.write((byte[]) value);
    } else if (value == null) {
        writeOctet('V');
    } else if (value instanceof List) {
        writeOctet('A');
        writeArray((List<?>) value);
    } else {
        throw new IllegalArgumentException("Invalid value type: " + value.getClass().getName());
    }
}

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

@Override
public int getCommonPrefixLength(UniqueIpResource other) {
    Validate.isTrue(getType() == other.getType(), "incompatible resource types");
    BigInteger temp = this.getValue().xor(other.getValue());
    return getType().getBitSize() - temp.bitLength();
}

From source file:uk.org.ukfederation.mda.validate.X509RSAOpenSSLBlacklistValidator.java

/** {@inheritDoc} */
@Override//from  ww  w. j a v  a  2  s  .c  o  m
public void validate(@Nonnull final X509Certificate cert, @Nonnull final Item<?> item,
        @Nonnull final String stageId) throws StageProcessingException {
    ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this);
    final PublicKey key = cert.getPublicKey();
    if ("RSA".equals(key.getAlgorithm())) {
        final RSAPublicKey rsaKey = (RSAPublicKey) key;
        final BigInteger modulus = rsaKey.getModulus();
        if (keySize == 0 || keySize == modulus.bitLength()) {
            final String value = openSSLDigest(modulus);
            if (blacklistedValues.contains(value)) {
                addError("RSA modulus included in key blacklist (" + value + ")", item, stageId);
            }
        }
    }
}

From source file:updater.builder.SoftwarePatchBuilder.java

public static void catalog(CommandLine line, Options options) throws ParseException, Exception {
    if (!line.hasOption("key")) {
        throw new Exception("Please specify the key file to use using --key");
    }//from w w  w.j a va  2  s.c  om
    if (!line.hasOption("output")) {
        throw new Exception("Please specify the path to output the XML file using --output");
    }

    String[] catalogArgs = line.getOptionValues("catalog");
    String keyArg = line.getOptionValue("key");
    String outputArg = line.getOptionValue("output");

    if (catalogArgs.length != 2) {
        throw new ParseException("Wrong arguments for 'catalog', expecting 2 arguments");
    }
    if (!catalogArgs[0].equals("e") && !catalogArgs[0].equals("d")) {
        throw new ParseException("Catalog mode should be either 'e' or 'd' but not " + catalogArgs[0]);
    }

    RSAKey rsaKey = RSAKey.read(Util.readFile(new File(keyArg)));

    System.out.println("Mode: " + (catalogArgs[0].equals("e") ? "encrypt" : "decrypt"));
    System.out.println("Catalog file: " + catalogArgs[1]);
    System.out.println("Key file: " + keyArg);
    System.out.println("Output file: " + outputArg);
    System.out.println();

    File in = new File(catalogArgs[1]);
    File out = new File(outputArg);
    BigInteger mod = new BigInteger(rsaKey.getModulus());

    if (catalogArgs[0].equals("e")) {
        BigInteger privateExp = new BigInteger(rsaKey.getPrivateExponent());

        RSAPrivateKey privateKey = CommonUtil.getPrivateKey(mod, privateExp);

        // compress
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        GZIPOutputStream gout = new GZIPOutputStream(bout);
        gout.write(Util.readFile(in));
        gout.finish();
        byte[] compressedData = bout.toByteArray();

        // encrypt
        int blockSize = mod.bitLength() / 8;
        byte[] encrypted = Util.rsaEncrypt(privateKey, blockSize, blockSize - 11, compressedData);

        // write to file
        Util.writeFile(out, encrypted);
    } else {
        BigInteger publicExp = new BigInteger(rsaKey.getPublicExponent());
        RSAPublicKey publicKey = CommonUtil.getPublicKey(mod, publicExp);

        // decrypt
        int blockSize = mod.bitLength() / 8;
        byte[] decrypted = Util.rsaDecrypt(publicKey, blockSize, Util.readFile(in));

        // decompress
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ByteArrayInputStream bin = new ByteArrayInputStream(decrypted);
        GZIPInputStream gin = new GZIPInputStream(bin);

        int byteRead;
        byte[] b = new byte[1024];
        while ((byteRead = gin.read(b)) != -1) {
            bout.write(b, 0, byteRead);
        }
        byte[] decompressedData = bout.toByteArray();

        // write to file
        Util.writeFile(out, decompressedData);
    }

    System.out.println("Manipulation succeed.");
}

From source file:com.github.fge.jsonschema.format.draftv3.UTCMillisecAttribute.java

@Override
public void validate(final ProcessingReport report, final MessageBundle bundle, final FullData data)
        throws ProcessingException {
    final JsonNode instance = data.getInstance().getNode();

    BigInteger epoch = instance.bigIntegerValue();

    if (epoch.signum() == -1) {
        report.warn(newMsg(data, bundle, "warn.format.epoch.negative").putArgument("value", instance));
        return;//from w  w  w  . j  ava  2 s  .  c  om
    }

    epoch = epoch.divide(ONE_THOUSAND);

    if (epoch.bitLength() > EPOCH_BITLENGTH)
        report.warn(newMsg(data, bundle, "warn.format.epoch.overflow").putArgument("value", instance));
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Test if a private key is extractable (could be stored).
 * /*  ww w  . j a  va  2  s.  c  om*/
 * @param privK
 *            key to test.
 * @return true if the key is extractable.
 */
public static boolean isPrivateKeyExtractable(final PrivateKey privK) {
    if (privK instanceof RSAPrivateKey) {
        final RSAPrivateKey rsa = (RSAPrivateKey) privK;
        final BigInteger result = rsa.getPrivateExponent();
        return result != null && result.bitLength() > 0;
    }
    if (privK instanceof ECPrivateKey) {
        final ECPrivateKey ec = (ECPrivateKey) privK;
        final BigInteger result = ec.getS();
        return result != null && result.bitLength() > 0;
    }
    if (privK instanceof DHPrivateKey) {
        final DHPrivateKey dh = (DHPrivateKey) privK;
        final BigInteger result = dh.getX();
        return result != null && result.bitLength() > 0;
    }
    if (privK instanceof DSAPrivateKey) {
        final DSAPrivateKey dsa = (DSAPrivateKey) privK;
        final BigInteger result = dsa.getX();
        return result != null && result.bitLength() > 0;
    }
    return false;
}

From source file:co.rsk.asm.EVMDissasembler.java

void printPush(OpCode op) {
    sb.append(' ').append(op.name()).append(' ');
    int nPush = op.val() - OpCode.PUSH1.val() + 1;
    String name = null;/*  ww  w. j a  va  2s.c  o m*/
    if ((block != null) && (helper != null) && (nPush == 4)) { // optimization, only find int32 label refs
        int labelId = block.getTagIdByPos(pc + 1, tagIterator);
        if (labelId >= 0) {
            name = getVisualLabelName(labelId);
            sb.append(name);
            if (printOffsets)
                sb.append(" ;");
        }
    }

    if ((printOffsets) || (name == null)) {
        byte[] data = Arrays.copyOfRange(code, pc + 1, pc + nPush + 1);
        BigInteger bi = new BigInteger(1, data);
        sb.append("0x").append(bi.toString(16));
        if (bi.bitLength() <= 32) {
            sb.append(" (").append(new BigInteger(1, data).toString()).append(") ");
        }
    }
}