方法依赖commons-codec包 maven的引入方式如下
1 <dependency> 2 <groupId>commons-codec</groupId> 3 <artifactId>commons-codec</artifactId> 4 <version>1.12</version> 5 </dependency>
1. 普通字符串转换为16进制字符串
1 /** 2 * 将普通字符串转换为16进制字符串 3 * @param str 普通字符串 4 * @param lowerCase 转换后的字母为是否为小写 可不传默认为true 5 * @param charset 编码格式 可不传默认为Charset.defaultCharset() 6 * @return 7 * @throws UnsupportedEncodingException 8 */ 9 public static String str2HexStr(String str,boolean lowerCase,String charset) throws UnsupportedEncodingException { 10 return Hex.encodeHexString(str.getBytes(charset),lowerCase); 11 }
2.16进制字符串转换为普通字符串
/** * 将16进制字符串转换为普通字符串 * @param hexStr 16进制字符串 * @param charset 编码格式 可不传默认为Charset.defaultCharset() * @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进制字符串转换为byte数组
1 /** 2 * 将16进制字符串转换为byte数组 3 * @param hexItr 16进制字符串 4 * @return 5 */ 6 public static byte[] hexItr2Arr(String hexItr) throws DecoderException { 7 return Hex.decodeHex(hexItr); 8 }
4. byte数组转换为16进制字符串
1 /** 2 * byte数组转化为16进制字符串 3 * @param arr 数组 4 * @param lowerCase 转换后的字母为是否为小写 可不传默认为true 5 * @return 6 */ 7 public static String arr2HexStr(byte[] arr,boolean lowerCase){ 8 return Hex.encodeHexString(arr, lowerCase); 9 }
5. 将普通字符串转换为指定编码格式的byte数组
1 /** 2 * 将普通字符串转换为指定格式的byte数组 3 * @param str 普通字符串 4 * @param charset 编码格式 可不传默认为Charset.defaultCharset() 5 * @return 6 * @throws UnsupportedEncodingException 7 */ 8 public static byte[] str2Arr(String str,String charset) throws UnsupportedEncodingException { 9 return str.getBytes(charset); 10 }
6. 将byte数组转换为指定编码格式的普通字符串
1 /** 2 * 将byte数组转换为指定编码格式的普通字符串 3 * @param arr byte数组 4 * @param charset 编码格式 可不传默认为Charset.defaultCharset() 5 * @return 6 * @throws UnsupportedEncodingException 7 */ 8 public static String arr2Str(byte[] arr,String charset) throws UnsupportedEncodingException { 9 return new String(arr,charset); 10 }