Java BigInteger to convertBigIntegerToNBytes( final BigInteger bigInteger, final int numBytes)

Here you can find the source of convertBigIntegerToNBytes( final BigInteger bigInteger, final int numBytes)

Description

Utility method to convert BigInteger to n element byte array

License

Open Source License

Parameter

Parameter Description
bigInteger big integer value that needs to be converted to byte
numBytes convert to number of bytes

Return

byte array containing n * 8 bits.

Declaration

public static byte[] convertBigIntegerToNBytes(
        final BigInteger bigInteger, final int numBytes) 

Method Source Code

//package com.java2s;
/**/*from  w w w.j a v  a 2 s .com*/
 * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

import java.math.BigInteger;
import java.util.Arrays;

public class Main {
    /**
     * Utility method to convert BigInteger to n element byte array
     *
     * @param bigInteger big integer value that needs to be converted to byte
     * @param numBytes convert to number of bytes
     * @return byte array containing n * 8 bits.
     */
    public static byte[] convertBigIntegerToNBytes(
            final BigInteger bigInteger, final int numBytes) {
        if (bigInteger == null) {
            return null;
        }
        byte[] inputArray = bigInteger.toByteArray();
        byte[] outputArray = new byte[numBytes];
        if (bigInteger.compareTo(BigInteger.ZERO) < 0) {
            Arrays.fill(outputArray, (byte) -1);
        } else {
            Arrays.fill(outputArray, (byte) 0);
        }
        System.arraycopy(inputArray,
                Math.max(0, inputArray.length - outputArray.length),
                outputArray,
                Math.max(0, outputArray.length - inputArray.length),
                Math.min(outputArray.length, inputArray.length));
        return outputArray;
    }
}

Related

  1. byteConvert32Bytes(BigInteger n)
  2. concat(BigInteger left, BigInteger right)
  3. convert(BigInteger value, int base, boolean extra)
  4. convertAllElementsToLong(P bigIntegers)
  5. convertBigIntegerIntoInetAddress(final BigInteger i)
  6. convertPositive(BigInteger bi)
  7. convertRealNumberBits(BigInteger source, int size, int direction)
  8. convertRepresentation(BigInteger b)
  9. convertToBase62String(BigInteger value)