Android String to Hex String Convert toHex(String txt)

Here you can find the source of toHex(String txt)

Description

Retrieve a string's hex format

License

Open Source License

Parameter

Parameter Description
txt the Original text,

Return

the hex format string

Declaration

public static String toHex(String txt) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*  w ww  .  j  av  a 2  s . c  o m*/
     * 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. toHex(byte[] buf)
  2. toHexString(String str)
  3. hexStr2Str(String hexStr)
  4. hexStringToCommonString(String hexString)
  5. toHex(String txt)
  6. parseHexStr2Byte(String hexStr)
  7. stringToHex(String string)
  8. str2HexStr(String str)
  9. str2HexStrExt(String str)