您编码为十六进制的数字必须表示字符的某些编码,例如UTF-8。因此,首先将字符串转换为以该编码方式表示字符串的字节[],然后将每个字节转换为十六进制。public static String hexadecimal(String input, String charsetName) throws UnsupportedEncodingException {
if (input == null) throw new NullPointerException();
return asHex(input.getBytes(charsetName));}private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
public static String asHex(byte[] buf){
char[] chars = new char[2 * buf.length];
for (int i = 0; i
{
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);}