Skip to content

Commit 78d89a2

Browse files
committed
字节数组转十六进制字符串
1 parent 5450852 commit 78d89a2

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

tang-commons/src/main/java/com/tang/commons/utils/ByteUtils.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,27 @@ public static String getSize(long size) {
2929
return formatter.format(size / Math.pow(1024, digitGroups)) + " " + sizeUnits.get(digitGroups);
3030
}
3131

32+
/**
33+
* 字节数组转十六进制字符串
34+
*
35+
* @param bytes 字节数组
36+
* @return 十六进制字符串
37+
*/
38+
public static String byteToHex(byte[] bytes) {
39+
// 每个字节用两个字符表示,所以字符串的长度是数组长度的两倍
40+
final var hexChars = new char[bytes.length * 2];
41+
final var hexDigits = new char[] {
42+
'0', '1', '2', '3', '4', '5', '6', '7',
43+
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
44+
};
45+
var index = 0;
46+
for (var b : bytes) {
47+
// 将字节的高位四个比特转换为相应的十六进制字符
48+
hexChars[index++] = hexDigits[(b >> 4) & 0xF];
49+
// 将字节的低位四个比特转换为相应的十六进制字符
50+
hexChars[index++] = hexDigits[b & 0xF];
51+
}
52+
return new String(hexChars);
53+
}
54+
3255
}

0 commit comments

Comments
 (0)