Java BigInteger to toIntegerBytes(final BigInteger bigInt)

Here you can find the source of toIntegerBytes(final BigInteger bigInt)

Description

to Integer Bytes

License

Mozilla Public License

Declaration

public static byte[] toIntegerBytes(final BigInteger bigInt) 

Method Source Code

//package com.java2s;
//License from project: Mozilla Public License 

import java.math.BigInteger;

public class Main {
    public static byte[] toIntegerBytes(final BigInteger bigInt) {
        int bitlen = bigInt.bitLength();
        // round bitlen
        bitlen = bitlen + 7 >> 3 << 3;
        final 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;//from w  ww  .ja v  a 2s.  c om
            len--;
        }
        final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
        final byte[] resizedBytes = new byte[bitlen / 8];
        System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
        return resizedBytes;
    }
}

Related

  1. toInt(BigInteger number)
  2. toInt(int length, BigInteger bi)
  3. toIntArray(BigInteger[] input)
  4. toInteger(BigInteger bi)
  5. toInteger(BigInteger integer)
  6. toMinimalByteArray(BigInteger value)
  7. toObject(BigInteger x)
  8. toPaddedBytes(BigInteger bi, int length)
  9. toPushbackReader(BigInteger x)