diff --git a/CHANGELOG.md b/CHANGELOG.md index 01739cbc4..b54d53073 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ ### 🐣新特性 * 【crypto 】 SmUtil.sm4统一返回类型(issue#I3YKD4@Gitee) * 【core 】 修改MapUtil.get传入null返回默认值而非null(issue#I3YKBC@Gitee) +* 【core 】 HexUtil增加hexToLong、hexToInt(issue#I3YQEV@Gitee) ### 🐞Bug修复 * 【core 】 修复RadixUtil.decode非static问题(issue#I3YPEH@Gitee) 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 965c59a18..1d9ec7cc5 100644 --- a/hutool-core/src/main/java/cn/hutool/core/util/HexUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/util/HexUtil.java @@ -148,7 +148,7 @@ public class HexUtil { if (StrUtil.isEmpty(hexStr)) { return hexStr; } - return decodeHexStr(hexStr.toCharArray(), charset); + return StrUtil.str(decodeHex(hexStr), charset); } /** @@ -197,11 +197,12 @@ public class HexUtil { } hexData = StrUtil.cleanBlank(hexData); - - final int len = hexData.length(); + int len = hexData.length(); if ((len & 0x01) != 0) { - throw new UtilException("Odd number of characters."); + hexData = "0" + hexData; + len = hexData.length(); +// throw new UtilException("Odd number of characters."); } final byte[] out = new byte[len >> 1]; @@ -327,6 +328,17 @@ public class HexUtil { return Integer.toHexString(value); } + /** + * 16进制字符串转为int + * + * @param value 16进制字符串 + * @return 16进制字符串int值 + * @since 5.7.4 + */ + public static int hexToInt(String value) { + return Integer.parseInt(value, 16); + } + /** * 转为16进制字符串 * @@ -338,6 +350,17 @@ public class HexUtil { return Long.toHexString(value); } + /** + * 16进制字符串转为long + * + * @param value 16进制字符串 + * @return long值 + * @since 5.7.4 + */ + public static long hexToLong(String value) { + return Long.parseLong(value, 16); + } + /** * 将byte值转为16进制并添加到{@link StringBuilder}中 * 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 a87b30ce5..0de502f5c 100644 --- a/hutool-core/src/test/java/cn/hutool/core/util/HexUtilTest.java +++ b/hutool-core/src/test/java/cn/hutool/core/util/HexUtilTest.java @@ -49,4 +49,11 @@ public class HexUtilTest { String formatHex = HexUtil.format(hex); Assert.assertEquals("e8 c6 70 38 0c b2 20 09 52 68 f4 02 21 fc 74 8f a6 ac 39 d6 e9 30 e6 3c 30 da 68 ba d9 7f 88 5d", formatHex); } + + @Test + public void decodeHexTest(){ + String s = HexUtil.encodeHexStr("6"); + final String s1 = HexUtil.decodeHexStr(s); + Assert.assertEquals("6", s1); + } }