mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-12-06 17:18:54 +08:00
Fix issue 4167
This commit is contained in:
parent
882f3923ce
commit
d821c410c6
@ -379,15 +379,24 @@ public class HexUtil {
|
|||||||
* @return 格式化后的字符串
|
* @return 格式化后的字符串
|
||||||
*/
|
*/
|
||||||
public static String format(final String hexStr, String prefix) {
|
public static String format(final String hexStr, String prefix) {
|
||||||
|
if (StrUtil.isEmpty(hexStr)) {
|
||||||
|
return StrUtil.EMPTY;
|
||||||
|
}
|
||||||
if (null == prefix) {
|
if (null == prefix) {
|
||||||
prefix = StrUtil.EMPTY;
|
prefix = StrUtil.EMPTY;
|
||||||
}
|
}
|
||||||
|
|
||||||
final int length = hexStr.length();
|
final int length = hexStr.length();
|
||||||
final StringBuilder builder = StrUtil.builder(length + length / 2 + (length / 2 * prefix.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) {
|
for (int i = 0; i < length; i++) {
|
||||||
builder.append(CharUtil.SPACE).append(prefix).append(hexStr.charAt(i)).append(hexStr.charAt(i + 1));
|
if (i % 2 == 0) {
|
||||||
|
if (i != 0) {
|
||||||
|
builder.append(CharUtil.SPACE);
|
||||||
|
}
|
||||||
|
builder.append(prefix);
|
||||||
|
}
|
||||||
|
builder.append(hexStr.charAt(i));
|
||||||
}
|
}
|
||||||
return builder.toString();
|
return builder.toString();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -116,4 +116,35 @@ public class HexUtilTest {
|
|||||||
final String hex3 = "#FF";
|
final String hex3 = "#FF";
|
||||||
assertEquals(new BigInteger("FF", 16), HexUtil.toBigInteger(hex3));
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user