Java Byte Array to Hex String bytesToHexString(byte[] bytes)

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

Description

Converts an array of bytes to a string representing the bytes in hexadecimal form.

License

Open Source License

Parameter

Parameter Description
bytes the array of bytes to be converted

Return

the string representing the bytes in hexadecimal form

Declaration

public static String bytesToHexString(byte[] bytes) 

Method Source Code

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

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

    /**/*from  ww w. j  a v a  2s . c  o  m*/
     * Converts an array of bytes to a string representing the bytes in hexadecimal form.
     * 
     * @param bytes the array of bytes to be converted
     * @return the string representing the bytes in hexadecimal form
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);

        for (byte b : bytes) {
            String hex = Integer.toHexString(0x0100 + (b & 0x00FF)).substring(1);

            if (hex.length() < 2) {
                sb.append("0");
            }

            sb.append(hex);
        }

        return sb.toString();
    }

    public static String toHexString(int i) {
        char[] buffer = new char[8];

        int index = 8;

        do {
            buffer[--index] = _HEX_DIGITS[i & 15];

            i >>>= 4;
        } while (i != 0);

        return new String(buffer, index, 8 - index);
    }

    public static String toHexString(long l) {
        char[] buffer = new char[16];

        int index = 16;

        do {
            buffer[--index] = _HEX_DIGITS[(int) (l & 15)];

            l >>>= 4;
        } while (l != 0);

        return new String(buffer, index, 16 - index);
    }

    public static String toHexString(Object obj) {
        if (obj instanceof Integer) {
            return toHexString(((Integer) obj).intValue());
        } else if (obj instanceof Long) {
            return toHexString(((Long) obj).longValue());
        } else {
            return String.valueOf(obj);
        }
    }

    /**
     * Returns the string value of the object.
     * 
     * @param obj the object whose string value is to be returned
     * @return the string value of the object
     * @see {@link String#valueOf(Object obj)}
     */
    public static String valueOf(Object obj) {
        return String.valueOf(obj);
    }
}

Related

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