From d821c410c6de49055c38695671c2055797f045c4 Mon Sep 17 00:00:00 2001 From: TouyamaRie Date: Fri, 28 Nov 2025 16:04:46 +0800 Subject: [PATCH] Fix issue 4167 --- .../java/cn/hutool/core/util/HexUtil.java | 15 +++++++-- .../java/cn/hutool/core/util/HexUtilTest.java | 31 +++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/hutool-core/src/main/java/cn/hutool/core/util/HexUtil.java b/hutool-core/src/main/java/cn/hutool/core/util/HexUtil.java index 0f209c483..1083e2897 100755 --- a/hutool-core/src/main/java/cn/hutool/core/util/HexUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/util/HexUtil.java @@ -379,15 +379,24 @@ public class HexUtil { * @return 格式化后的字符串 */ public static String format(final String hexStr, String prefix) { + if (StrUtil.isEmpty(hexStr)) { + return StrUtil.EMPTY; + } if (null == prefix) { prefix = StrUtil.EMPTY; } final int length = hexStr.length(); final StringBuilder builder = StrUtil.builder(length + length / 2 + (length / 2 * prefix.length())); - builder.append(prefix).append(hexStr.charAt(0)).append(hexStr.charAt(1)); - for (int i = 2; i < length - 1; i += 2) { - builder.append(CharUtil.SPACE).append(prefix).append(hexStr.charAt(i)).append(hexStr.charAt(i + 1)); + + for (int i = 0; i < length; i++) { + if (i % 2 == 0) { + if (i != 0) { + builder.append(CharUtil.SPACE); + } + builder.append(prefix); + } + builder.append(hexStr.charAt(i)); } return builder.toString(); } diff --git a/hutool-core/src/test/java/cn/hutool/core/util/HexUtilTest.java b/hutool-core/src/test/java/cn/hutool/core/util/HexUtilTest.java index b37f4b3ff..f8e7a0745 100755 --- a/hutool-core/src/test/java/cn/hutool/core/util/HexUtilTest.java +++ b/hutool-core/src/test/java/cn/hutool/core/util/HexUtilTest.java @@ -116,4 +116,35 @@ public class HexUtilTest { final String hex3 = "#FF"; assertEquals(new BigInteger("FF", 16), HexUtil.toBigInteger(hex3)); } + + @Test + public void testFormatEmpty() { + String result = HexUtil.format(""); + assertEquals("", result); + } + + @Test + public void testFormatSingleChar() { + String result = HexUtil.format("1"); + assertEquals("1", result); + } + + @Test + public void testFormatOddLength() { + String result = HexUtil.format("123"); + assertEquals("12 3", result); + } + + @Test + public void testFormatWithPrefixSingleChar() { + String result = HexUtil.format("1", "0x"); + assertEquals("0x1", result); + } + + @Test + public void testFormatWithPrefixOddLength() { + String result = HexUtil.format("123", "0x"); + assertEquals("0x12 0x3", result); + } + }