Java BigInteger to toByteArray(final BigInteger b)

Here you can find the source of toByteArray(final BigInteger b)

Description

Converts a BigInteger to a little endian 32 byte representation.

License

Open Source License

Parameter

Parameter Description
b The BigInteger.

Return

The 32 byte representation.

Declaration

public static byte[] toByteArray(final BigInteger b) 

Method Source Code


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

import java.math.BigInteger;

public class Main {
    /**/*w ww  . j a  va  2 s  .  c  om*/
     * Converts a BigInteger to a little endian 32 byte representation.
     *
     * @param b The BigInteger.
     * @return The 32 byte representation.
     */
    public static byte[] toByteArray(final BigInteger b) {
        if (b.compareTo(BigInteger.ONE.shiftLeft(256)) >= 0) {
            throw new RuntimeException("only numbers < 2^256 are allowed");
        }
        final byte[] bytes = new byte[32];
        final byte[] original = b.toByteArray();

        // Although b < 2^256, original can have length > 32 with some bytes set to 0.
        final int offset = original.length > 32 ? original.length - 32 : 0;
        for (int i = 0; i < original.length - offset; i++) {
            bytes[original.length - i - offset - 1] = original[i + offset];
        }

        return bytes;
    }
}

Related

  1. getUnsignedBigIntegerAsHex(BigInteger bi)
  2. getUnsignedBytes(BigInteger number, int length)
  3. stringForBig(BigInteger big, int sigchars)
  4. toBase_128(BigInteger val)
  5. toByteArray(BigInteger i)
  6. toByteArray(final BigInteger value, final int numBytes)
  7. toByteArrayUnsigned(BigInteger bi)
  8. toBytes(BigInteger bigInt, int expectedSize)
  9. toBytesUnsigned(final BigInteger bigInt)