1. 将普通字符串转换为16进制字符串
/**
* 将普通字符串转换为16进制字符串
* @param str 普通字符串
* @param charset 编码格式,一般传UTF-8
* @return
* @throws UnsupportedEncodingException
*/
public static String str2HexStr(String str,String charset) throws UnsupportedEncodingException {
return Hex.encodeHexString(str.getBytes(charset));
}
2.将16进制字符串转换为普通字符串
/**
* 将16进制字符串转换为普通字符串
* @param hexStr 16进制字符串
* @param charset 编码格式
* @return
* @throws DecoderException
* @throws UnsupportedEncodingException
*/
public static String hexStr2Str(String hexStr,String charset) throws DecoderException, UnsupportedEncodingException {
byte[] bytes = Hex.decodeHex(hexStr);
return new String(bytes,charset);
}
3.16进制字符转数组
/**
* 16进制字符转数组
* @param hex16Str
* @return
*/
public static byte[] conver16HexToByte(String hex16Str){
char[] chars = hex16Str.toCharArray();
byte[] b = new byte[chars.length/2];
for (int i = 0; i < b.length; i++) {
int pos = i * 2;
b[i] = (byte) ("0123456789ABCDEF".indexOf(chars[pos]) << 4 | "0123456789ABCDEF".indexOf(chars[pos+1]));
}
return b;
}
4.数组转16进制字符
/**
* 数组转16进制字符
* @param bytes
* @return
*/
public static String bytesToHex(byte[] bytes){
StringBuffer sb =new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if(hex.length() < 2){
sb.append(0);
}
sb.append(hex);
}
return sb.toString().toUpperCase();
}