Here you can find the source of bigIntegerToBytes(BigInteger b, int numBytes)
Parameter | Description |
---|---|
b | the integer to format into a byte array |
numBytes | the desired size of the resulting byte array |
public static byte[] bigIntegerToBytes(BigInteger b, int numBytes)
//package com.java2s; /*//from w w w . ja v a 2s . com * This file is part of RskJ * Copyright (C) 2017 RSK Labs Ltd. * (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.math.BigInteger; public class Main { public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * 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) { if (b == null) { return EMPTY_BYTE_ARRAY; } 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; } /** * Omitting sign indication byte. * <br><br> * Instead of {@link org.bouncycastle.util.BigIntegers#asUnsignedByteArray(BigInteger)} * <br>we use this custom method to avoid an empty array in case of BigInteger.ZERO * * @param value - any big integer number. A <code>null</code>-value will return <code>null</code> * @return A byte array without a leading zero byte if present in the signed encoding. * BigInteger.ZERO will return an array with length 1 and byte-value 0. */ public static byte[] bigIntegerToBytes(BigInteger value) { if (value == null) { return EMPTY_BYTE_ARRAY; } byte[] data = value.toByteArray(); if (data.length != 1 && data[0] == 0) { byte[] tmp = new byte[data.length - 1]; System.arraycopy(data, 1, tmp, 0, tmp.length); data = tmp; } return data; } }