Java BigInteger to bigIntegerToBytes(BigInteger b, int numBytes)

Here you can find the source of bigIntegerToBytes(BigInteger b, int numBytes)

Description

The regular java.math.BigInteger#toByteArray() method isn't quite what we often need: it appends a leading zero to indicate that the number is positive and may need padding.

License

Apache License

Parameter

Parameter Description
b the integer to format into a byte array
numBytes the desired size of the resulting byte array

Return

numBytes byte long array.

Declaration

public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) 

Method Source Code

//package com.java2s;
/*// w  w w  .j a v a  2s . c o  m
 * Copyright 2011 Google Inc.
 * Copyright 2014 Andreas Schildbach
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.math.BigInteger;

public class Main {
    /**
     * The regular {@link java.math.BigInteger#toByteArray()} method isn't quite what we often need: it appends a
     * leading zero to indicate that the number is positive and may need padding.
     *
     * @param b the integer to format into a byte array
     * @param numBytes the desired size of the resulting byte array
     * @return numBytes byte long array.
     */
    public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) {
        byte[] bytes = new byte[numBytes];
        byte[] biBytes = b.toByteArray();
        int start = (biBytes.length == numBytes + 1) ? 1 : 0;
        int length = Math.min(biBytes.length, numBytes);
        System.arraycopy(biBytes, start, bytes, numBytes - length, length);
        return bytes;
    }
}

Related

  1. bigIntegerToBase64(BigInteger value)
  2. bigIntegerToBitArray(BigInteger x, int length)
  3. BigIntegerToByteArrayWithoutSign(BigInteger value)
  4. bigIntegerToBytes(BigInteger b, int numBytes)
  5. bigIntegerToBytes(BigInteger b, int numBytes)
  6. bigIntegerToBytes(BigInteger b, int numBytes)
  7. bigIntegerToBytes(BigInteger integer)
  8. bigIntegerToBytes(BigInteger n, byte[] data, int[] offset)
  9. bigIntegerToBytes(final BigInteger bigInteger)