Java BigInteger to toByteArray(final BigInteger value, final int numBytes)

Here you can find the source of toByteArray(final BigInteger value, final int numBytes)

Description

Converts a BigInteger to a little endian byte array.

License

Open Source License

Parameter

Parameter Description
value The value to convert.
numBytes The number of bytes in the destination array.

Return

The resulting little endian byte array.

Declaration

public static byte[] toByteArray(final BigInteger value, final int numBytes) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.math.BigInteger;

public class Main {
    /**//from   w  w w .j  a v  a 2  s.  c om
     * Converts a BigInteger to a little endian byte array.
     *
     * @param value The value to convert.
     * @param numBytes The number of bytes in the destination array.
     * @return The resulting little endian byte array.
     */
    public static byte[] toByteArray(final BigInteger value, final int numBytes) {
        final byte[] outputBytes = new byte[numBytes];
        final byte[] bigIntegerBytes = value.toByteArray();

        int copyStartIndex = (0x00 == bigIntegerBytes[0]) ? 1 : 0;
        int numBytesToCopy = bigIntegerBytes.length - copyStartIndex;
        if (numBytesToCopy > numBytes) {
            copyStartIndex += numBytesToCopy - numBytes;
            numBytesToCopy = numBytes;
        }

        for (int i = 0; i < numBytesToCopy; ++i) {
            outputBytes[i] = bigIntegerBytes[copyStartIndex + numBytesToCopy - i - 1];
        }

        return outputBytes;
    }
}

Related

  1. getUnsignedBytes(BigInteger number, int length)
  2. stringForBig(BigInteger big, int sigchars)
  3. toBase_128(BigInteger val)
  4. toByteArray(BigInteger i)
  5. toByteArray(final BigInteger b)
  6. toByteArrayUnsigned(BigInteger bi)
  7. toBytes(BigInteger bigInt, int expectedSize)
  8. toBytesUnsigned(final BigInteger bigInt)
  9. toDecimal(BigInteger value, byte[] buffer, int offset, int length, int itemLength, byte pos)