Android Byte Array to Hex Convert toHex(byte[] buf)

Here you can find the source of toHex(byte[] buf)

Description

Retrieve the string format of a byte data.

License

Open Source License

Parameter

Parameter Description
buf the byte source.

Return

the string format.

Declaration

public static String toHex(byte[] buf) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*  ww w  .j  av  a  2s  .c  om*/
     * Padding HEX string.
     */
    public static final String HEX = "0123456789ABCDEF";

    /**
     * Retrieve a string's hex format
     * @param txt the Original text,
     * @return the hex format string
     */
    public static String toHex(String txt) {
        return toHex(txt.getBytes());
    }

    /**
     * Retrieve the string format of a byte data.
     * @param buf the byte source.
     * @return the string format.
     */
    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    /**
     * utility function to transfer the byte data.
     * @param sb the string to be appended new character.
     * @param b the byte data
     */
    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }
}

Related

  1. toHexStringArray(byte[] data, int offset, int length)
  2. convertToHexString(byte[] input)
  3. dumpHex(byte[] bytes)
  4. getBinaryStrFromByteArr(byte[] bArr)
  5. toHex(byte[] buf)
  6. byte2hex(byte[] b)
  7. byte2hex(byte[] b)
  8. hexEncode(byte[] data)
  9. encodeHex(byte[] data)