Java Hex Calculate toHexString(byte[] bytes)

Here you can find the source of toHexString(byte[] bytes)

Description

Converts a byte array to a string of hexadecimal characters.

License

GNU General Public License

Parameter

Parameter Description
bytes the byte array

Return

hexadecimal representation

Declaration

public static String toHexString(byte[] bytes) 

Method Source Code

//package com.java2s;
// License: GPL. For details, see LICENSE file.

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

    /**//from w  w  w  . j a  v  a  2  s.  com
     * Converts a byte array to a string of hexadecimal characters.
     * Preserves leading zeros, so the size of the output string is always twice
     * the number of input bytes.
     * @param bytes the byte array
     * @return hexadecimal representation
     */
    public static String toHexString(byte[] bytes) {

        if (bytes == null) {
            return "";
        }

        final int len = bytes.length;
        if (len == 0) {
            return "";
        }

        char[] hexChars = new char[len * 2];
        for (int i = 0, j = 0; i < len; i++) {
            final int v = bytes[i];
            hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
            hexChars[j++] = HEX_ARRAY[v & 0xf];
        }
        return new String(hexChars);
    }
}

Related

  1. toHexString(byte[] bytes)
  2. toHexString(byte[] bytes)
  3. toHexString(byte[] bytes)
  4. toHexString(byte[] bytes)
  5. toHexString(byte[] bytes)
  6. toHexString(byte[] bytes)
  7. toHexString(byte[] bytes)
  8. toHexString(byte[] bytes)
  9. toHexString(byte[] bytes)