Java Hex Calculate toHex(final byte... bin)

Here you can find the source of toHex(final byte... bin)

Description

Encodes a series of bytes into a hexidecimal string (potentially with leading zeroes) with no separators between each source byte

License

Open Source License

Parameter

Parameter Description
bin a parameter

Declaration

public static final String toHex(final byte... bin) 

Method Source Code

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

public class Main {
    private static final char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
            'f' };

    /**//from   ww w  .ja  v  a  2 s.  com
     * Encodes a series of bytes into a hexidecimal string (potentially with leading zeroes) with no separators between each
     * source byte
     *
     * @param bin
     *
     * @return
     */
    public static final String toHex(final byte... bin) {
        if (bin == null || bin.length == 0)
            return "";

        final char[] buffer = new char[bin.length * 2];

        // i tracks input position, j tracks output position
        for (int i = 0, j = 0; i < bin.length; i++) {
            final byte b = bin[i];

            buffer[j++] = hex[(b >> 4) & 0x0F];
            buffer[j++] = hex[b & 0x0F];
        }

        return new String(buffer);
    }

    /**
     * Encodes a series of bytes into a hexidecimal string with each source byte (represented in the output as a 2 digit
     * hexidecimal pair) separated by <code>separator</code><br />
     *
     * @param separator
     *       The character to insert between each byte (for example, <code>':'</code>)
     * @param bin
     *       the series of bytes to encode
     *
     * @return a hexidecimal string with each source byte (represented in the output as a 2 digit hexidecimal pair) separated by
     * <code>separator</code>
     */
    public static final String toHex(final char separator, final byte... bin) {
        if (bin == null || bin.length == 0)
            return "";

        char[] buffer = new char[(bin.length * 3) - 1];
        int end = bin.length - 1;
        int base = 0; // Store the index of buffer we're inserting into
        for (int i = 0; i < bin.length; i++) {
            byte b = bin[i];

            buffer[base++] = hex[(b >> 4) & 0x0F];
            buffer[base++] = hex[b & 0x0F];
            if (i != end)
                buffer[base++] = separator;
        }

        return new String(buffer);
    }
}

Related

  1. toHex(byte[] value)
  2. toHex(byte[] value)
  3. toHex(char c)
  4. toHex(final byte b)
  5. toHex(final byte b)
  6. toHex(final byte[] ba)
  7. toHex(final byte[] ba)
  8. toHex(final byte[] bytes)
  9. toHex(final byte[] bytes)