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();
}