Java Hex Calculate toHexString(byte bytes[])

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

Description

Convert byte array to hex string

License

Open Source License

Parameter

Parameter Description
bytes a parameter

Declaration

public static String toHexString(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' };

    /**/*w  ww .  j  ava  2s . c  o m*/
     * Convert byte array to hex string
     * @param bytes
     * @return
     */
    public static String toHexString(byte bytes[]) {
        return toHexString(bytes, "");
    }

    /**
     * Convert byte array to hex string, separating each byte with given separator.
     * @param bytes
     * @param separator
     * @return
     */
    public static String toHexString(byte bytes[], String separator) {
        byte ch = 0x00;
        int i = 0;
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        StringBuffer out = new StringBuffer(bytes.length * 2 + (bytes.length - 1) * separator.length());
        while (i < bytes.length) {
            if (i != 0) {
                out.append(separator);
            }
            ch = (byte) (bytes[i] & 0xF0); // strip off high nibble
            ch = (byte) (ch >>> 4); // shift the bits down
            ch = (byte) (ch & 0x0F); // must do this if high order bit is on
            out.append(HEX_DIGITS[(int) ch]); // convert the nibble to a hex digit
            ch = (byte) (bytes[i] & 0x0F); // strip off low nibble
            out.append(HEX_DIGITS[(int) ch]); // convert the nibble to a hex digit
            i++;
        }
        return out.toString();
    }
}

Related

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