Java BigInteger to toFixedLenByteArray(BigInteger x, int resultByteLen)

Here you can find the source of toFixedLenByteArray(BigInteger x, int resultByteLen)

Description

Fit (stretch or shrink) the given positive BigInteger into a byte[] of resultByteLen bytes without losing precision.

License

Open Source License

Declaration

public static byte[] toFixedLenByteArray(BigInteger x, int resultByteLen) 

Method Source Code


//package com.java2s;
/* $Id: Util.java,v 1.3 2003/02/07 15:06:24 gelderen Exp $
 *
 * Copyright (C) 2000 The Cryptix Foundation Limited.
 * All rights reserved.//ww  w.  j a v  a 2s  .  co m
 * 
 * Use, modification, copying and distribution of this software is subject 
 * the terms and conditions of the Cryptix General Licence. You should have 
 * received a copy of the Cryptix General Licence along with this library; 
 * if not, you can download a copy from http://www.cryptix.org/ .
 */

import java.math.BigInteger;

public class Main {
    /**
     * Fit (stretch or shrink) the given positive BigInteger into a 
     * byte[] of resultByteLen bytes without losing precision.
     *
     * @trhows IllegalArgumentException
     *         If x negative, or won't fit in requested number of bytes.
     */
    public static byte[] toFixedLenByteArray(BigInteger x, int resultByteLen) {

        if (x.signum() != 1)
            throw new IllegalArgumentException("BigInteger not positive.");

        byte[] x_bytes = x.toByteArray();
        int x_len = x_bytes.length;

        if (x_len <= 0)
            throw new IllegalArgumentException("BigInteger too small.");

        /*
         * The BigInteger contract specifies that we now have at most one
         * superfluous leading zero byte:
         */
        int x_off = (x_bytes[0] == 0) ? 1 : 0;
        x_len -= x_off;

        /*
         * Check whether the BigInteger will fit in the requested byte length.
         */
        if (x_len > resultByteLen)
            throw new IllegalArgumentException("BigInteger too large.");

        /*
         * Now stretch or shrink the encoding to fit in resByteLen bytes.
         */
        byte[] res_bytes = new byte[resultByteLen];
        int res_off = resultByteLen - x_len;
        System.arraycopy(x_bytes, x_off, res_bytes, res_off, x_len);
        return res_bytes;
    }
}

Related

  1. toByteArrayUnsigned(BigInteger bi)
  2. toBytes(BigInteger bigInt, int expectedSize)
  3. toBytesUnsigned(final BigInteger bigInt)
  4. toDecimal(BigInteger value, byte[] buffer, int offset, int length, int itemLength, byte pos)
  5. toEvenLengthHex(BigInteger value)
  6. toInt(BigInteger number)
  7. toInt(int length, BigInteger bi)
  8. toIntArray(BigInteger[] input)
  9. toInteger(BigInteger bi)