普通的bytesToHexString:
利用Integer.toHexString()来实现
(以下代码源于网络)
public static String bytesToHexString(byte... src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
高效的bytesToHexString:
通过对一个只读数组hexArray进行读取来实现
(以下代码源于网络)
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String byteArrToHex(byte... bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
测试代码:
随机生成特定长度的byte数组,传进算法用System.nanoTime()测试执行时间。循环执行25次取平均值
public static void main(String[] args) {
int len = 500000;
byte[] bytes = new byte[len];
Random r = new Random();
r.nextBytes(bytes);
long time;
long sum1 = 0;
long sum2 = 0;
for (int i = 0; i < 25; i++) {
time = System.nanoTime();
byteArrToHex(bytes);
sum1 += (System.nanoTime() - time);
time = System.nanoTime();
bytesToHexString(bytes);
sum2 += (System.nanoTime() - time);
}
System.out.println("fun1: " + (sum1 / 25));
System.out.println("fun2: " + (sum2 / 25));
}
测试结果:
当长度len为1时:
fun1: 1228
fun2: 3709
当长度len为500时:
fun1: 23938
fun2: 124859
当长度len为1000000时:
fun1: 3388851
fun2: 34042681
测试环境:
CPU:Intel Core I5-8250U
RAM:8GB
操作系统:Win10 家庭版 17134.472
JDK:1.8.0_181
总结:方法2 byteArrToHex 的执行效率远高于方法1 bytesToHexString