1.准备工作
import java.util.Arrays;
/**
* Byte[]与hex的相互转换
* @explain
* @author Marydon
* @creationTime 2018年6月11日下午2:29:11
* @version 1.0
* @since
* @email marydon20170307@163.com
*/
public class ByteUtils {
// 16进制字符
private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
2.byte类型数组转化成16进制字符串
方法一
/**
* 方法一:将byte类型数组转化成16进制字符串
* @explain 字符串拼接
* @param bytes
* @return
*/
public static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
int num;
for (byte b : bytes) {
num = b < 0 ? 256 + b : b;
sb.append(HEX_CHAR[num / 16]).append(HEX_CHAR[num % 16]);
}
return sb.toString();
}
方法二
/**
* 方法二: byte[] to hex string
* @explain 使用数组
* @param bytes
* @return
*/
public static String toHexString2(byte[] bytes) {
// 一个byte为8位,可用两个十六进制位表示
char[] buf = new char[bytes.length * 2];
int a = 0;
int index = 0;