Java BigInteger Calculate getBytes(BigInteger big, int bitlen)

Here you can find the source of getBytes(BigInteger big, int bitlen)

Description

Returns a byte-array representation of a BigInteger .

License

Apache License

Parameter

Parameter Description
big <code>BigInteger<code> to be converted
bitlen <code>int<code> the desired length in bits of the representation

Return

a byte array with bitlen bits of big

Declaration

static final byte[] getBytes(BigInteger big, int bitlen) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.math.BigInteger;

public class Main {
    /**//from   ww  w  .  j  a  v  a  2  s.com
     * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
     * No sign-bit is output.
     *
     * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
     * returns eventually longer arrays because of the leading sign-bit.
     *
     * @param big <code>BigInteger<code> to be converted
     * @param bitlen <code>int<code> the desired length in bits of the representation
     * @return a byte array with <code>bitlen</code> bits of <code>big</code>
     */
    static final byte[] getBytes(BigInteger big, int bitlen) {

        //round bitlen
        bitlen = ((bitlen + 7) >> 3) << 3;

        if (bitlen < big.bitLength()) {
            throw new IllegalArgumentException("IllegalBitlength");
        }

        byte[] bigBytes = big.toByteArray();

        if (((big.bitLength() % 8) != 0) && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
            return bigBytes;
        }

        // some copying needed
        int startSrc = 0; // no need to skip anything
        int bigLen = bigBytes.length; //valid length of the string

        if ((big.bitLength() % 8) == 0) { // correct values
            startSrc = 1; // skip sign bit

            bigLen--; // valid length of the string
        }

        int startDst = bitlen / 8 - bigLen; //pad with leading nulls
        byte[] resizedBytes = new byte[bitlen / 8];

        System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);

        return resizedBytes;
    }
}

Related

  1. gcdEuclides(BigInteger a, BigInteger b)
  2. gcdExtended(BigInteger p, BigInteger q)
  3. getAddressText(BigInteger address)
  4. getByteArrayFromBigIntegerArray(Object value)
  5. getBytes(BigInteger bi, int minLen)
  6. getBytesWithoutSign(BigInteger arg)
  7. getClearExpPipe(BigInteger M)
  8. getCreateLocalNextHopJobKey(Long vpnId, BigInteger dpnId, String prefix)
  9. getDateOf(BigInteger fileTime)