浏览代码

add method

Looly 5 年之前
父节点
当前提交
ab410d2e93

+ 1 - 0
CHANGELOG.md

@@ -10,6 +10,7 @@
 * 【core   】     增加ArrayUtil.isSub、indexOfSub、lastIndexOfSub方法(issue#I23O1K@Gitee)
 * 【extra  】     增加ValidationUtil(pr#207@Gitee)
 * 【core   】     反射调用支持传递参数的值为null(pr#1205@Github)
+* 【core   】     HexUtil增加format方法(issue#I245NF@Gitee)
 
 ### Bug修复
 * 【core   】     修复DateUtil.current使用System.nanoTime的问题(issue#1198@Github)

+ 24 - 3
hutool-core/src/main/java/cn/hutool/core/util/HexUtil.java

@@ -199,7 +199,8 @@ public class HexUtil {
 		if (StrUtil.isEmpty(hexStr)) {
 			return null;
 		}
-		hexStr = StrUtil.removeAll(hexStr, ' ');
+
+		hexStr = StrUtil.cleanBlank(hexStr);
 		return decodeHex(hexStr.toCharArray());
 	}
 
@@ -342,17 +343,37 @@ public class HexUtil {
 
 	/**
 	 * Hex(16进制)字符串转为BigInteger
+	 *
 	 * @param hexStr Hex(16进制字符串)
 	 * @return {@link BigInteger}
 	 * @since 5.2.0
 	 */
-	public static BigInteger toBigInteger(String hexStr){
-		if(null == hexStr){
+	public static BigInteger toBigInteger(String hexStr) {
+		if (null == hexStr) {
 			return null;
 		}
 		return new BigInteger(hexStr, 16);
 	}
 
+	/**
+	 * 格式化Hex字符串,结果为每2位加一个空格,类似于:
+	 * <pre>
+	 *     e8 8c 67 03 80 cb 22 00 95 26 8f
+	 * </pre>
+	 *
+	 * @param hexStr Hex字符串
+	 * @return 格式化后的字符串
+	 */
+	public static String format(String hexStr) {
+		final int length = hexStr.length();
+		final StringBuilder builder = StrUtil.builder(length + length / 2);
+		builder.append(hexStr.charAt(0)).append(hexStr.charAt(1));
+		for (int i = 1; i < length - 1; i += 2) {
+			builder.append(CharUtil.SPACE).append(hexStr.charAt(i)).append(hexStr.charAt(i + 1));
+		}
+		return builder.toString();
+	}
+
 	// ---------------------------------------------------------------------------------------- Private method start
 
 	/**

+ 7 - 0
hutool-core/src/test/java/cn/hutool/core/util/HexUtilTest.java

@@ -42,4 +42,11 @@ public class HexUtilTest {
 		Assert.assertArrayEquals(HexUtil.decodeHex(str),
 				HexUtil.decodeHex(str.toUpperCase()));
 	}
+
+	@Test
+	public void formatHexTest(){
+		String hex = "e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885d";
+		String formatHex = HexUtil.format(hex);
+		Assert.assertEquals("e8 8c 67 03 80 cb 22 00 95 26 8f 40 22 1f c7 48 fa 6a c3 9d 6e 93 0e 63 c3 0d a6 8b ad 97 f8 85", formatHex);
+	}
 }