Java BigInteger to toBytesUnsigned(final BigInteger bigInt)

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

Description

Returns a byte array representation of the specified big integer without the sign bit.

License

Apache License

Parameter

Parameter Description
bigInt The big integer to be converted. Must not be null .

Return

A byte array representation of the big integer, without the sign bit.

Declaration

public static byte[] toBytesUnsigned(final BigInteger bigInt) 

Method Source Code


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

import java.math.BigInteger;

public class Main {
    /**/*  ww w . ja  va 2s. c o  m*/
     * Returns a byte array representation of the specified big integer 
     * without the sign bit.
     * 
     * @param bigInt The big integer to be converted. Must not be
     *               {@code null}.
     *
     * @return A byte array representation of the big integer, without the
     *         sign bit.
     */
    public static byte[] toBytesUnsigned(final BigInteger bigInt) {

        // Copied from Apache Commons Codec 1.8

        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;
            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. toByteArray(BigInteger i)
  2. toByteArray(final BigInteger b)
  3. toByteArray(final BigInteger value, final int numBytes)
  4. toByteArrayUnsigned(BigInteger bi)
  5. toBytes(BigInteger bigInt, int expectedSize)
  6. toDecimal(BigInteger value, byte[] buffer, int offset, int length, int itemLength, byte pos)
  7. toEvenLengthHex(BigInteger value)
  8. toFixedLenByteArray(BigInteger x, int resultByteLen)
  9. toInt(BigInteger number)