Java BigInteger to bigIntegerToUnsignedByteArray(BigInteger a, int len)

Here you can find the source of bigIntegerToUnsignedByteArray(BigInteger a, int len)

Description

big Integer To Unsigned Byte Array

License

Open Source License

Declaration

public static final byte[] bigIntegerToUnsignedByteArray(BigInteger a, int len) throws NumberFormatException 

Method Source Code

//package com.java2s;
/**/*from ww w.j  a  va  2s.c om*/
 * Hoofprints - An Extensible Testbed for Route-Servers
 * Copyright (C) 2009 Sebastian Spies
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU 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[] bigIntegerToUnsignedByteArray(BigInteger a, int len) throws NumberFormatException {
        byte[] buf = new byte[len];

        if (a.bitLength() > len * 8)
            throw new NumberFormatException("BigInteger doesn't fit into array");

        byte[] b = a.toByteArray();

        if (b.length == len + 1)
            if (b[0] == 0)
                for (int i = 0; i < buf.length; i++)
                    buf[i] = b[i + 1];
            else
                throw new NumberFormatException("Internal Error");
        else if (b.length <= len)
            for (int i = 0; i < b.length; i++)
                buf[buf.length - 1 - i] = b[b.length - 1 - i];
        else
            throw new NumberFormatException("Internal Error");

        return buf;
    }
}

Related

  1. bigIntegerToDigits(BigInteger n)
  2. BigIntegerToEightBytes(BigInteger value)
  3. bigIntegerToHex(final BigInteger bigInteger)
  4. bigIntegerToList(BigInteger number)
  5. bigIntegerToString(final BigInteger value)
  6. bigIntToArray(BigInteger data)
  7. bigIntToHash(BigInteger keyValue)
  8. bigIntToHex(BigInteger big)
  9. bigIntToIpV6(BigInteger argInt)