Java BigInteger to biToHex(BigInteger bi)

Here you can find the source of biToHex(BigInteger bi)

Description

Turn a BigInteger into a hex string.

License

Open Source License

Declaration

public static String biToHex(BigInteger bi) 

Method Source Code

//package com.java2s;
/*/*from w w w. jav a 2 s .  c o m*/
 *   This file is part of dhcp4java, a DHCP API for the Java language.
 *   (c) 2006 Stephan Hadinger
 *
 *   This library 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 2.1 of the License, or (at your option) any later version.
 *
 *   This library 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 library; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

import java.math.BigInteger;

public class Main {
    /**
     * Turn a BigInteger into a hex string.
     * BigInteger.toString(16) NPEs on Sun JDK 1.4.2_05. :<
     * The bugs in their Big* are getting seriously irritating...
     */
    public static String biToHex(BigInteger bi) {
        return bytesToHex(bi.toByteArray());
    }

    /**
     * Converts a byte array into a string of upper case hex chars.
     *
     *  <at> param bs
     *            A byte array
     *  <at> param off
     *            The index of the first byte to read
     *  <at> param length
     *            The number of bytes to read.
     *  <at> return the string of hex chars.
     */
    public static String bytesToHex(byte[] bs, int off, int length) {
        StringBuffer sb = new StringBuffer(length * 2);
        bytesToHexAppend(bs, off, length, sb);
        return sb.toString();
    }

    public static String bytesToHex(byte[] bs) {
        return bytesToHex(bs, 0, bs.length);
    }

    public static void bytesToHexAppend(byte[] bs, int off, int length, StringBuffer sb) {
        sb.ensureCapacity(sb.length() + length * 2);
        for (int i = off; i < (off + length) && i < bs.length; i++) {
            sb.append(Character.forDigit((bs[i] >>> 4) & 0xf, 16)).append(Character.forDigit(bs[i] & 0xf, 16));
        }
    }
}

Related

  1. bigIntToHash(BigInteger keyValue)
  2. bigIntToHex(BigInteger big)
  3. bigIntToIpV6(BigInteger argInt)
  4. BigIntToPaddedByteArray(BigInteger bi, int length)
  5. bigIntToSortableBytes(BigInteger bigInt, int bigIntSize, byte[] result, int offset)
  6. byteConvert32Bytes(BigInteger n)
  7. concat(BigInteger left, BigInteger right)
  8. convert(BigInteger value, int base, boolean extra)
  9. convertAllElementsToLong(P bigIntegers)