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 a40d12c41..ac2f55e03 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 @@ -296,6 +296,20 @@ public class HexUtil { return Integer.toHexString(value); } + /** + * 去除十六进制字符串的常见前缀 0x、0X、# + * + * @param s 十六进制字符串 + * @return 去除前缀后的字符串 + */ + private static String stripHexPrefix(String s) { + if (s == null) return null; + s = s.trim(); + if (s.startsWith("0x") || s.startsWith("0X")) return s.substring(2); + if (s.startsWith("#")) return s.substring(1); + return s; + } + /** * 16进制字符串转为int * @@ -304,7 +318,7 @@ public class HexUtil { * @since 5.7.4 */ public static int hexToInt(String value) { - return Integer.parseInt(value, 16); + return Integer.parseInt(stripHexPrefix(value), 16); } /** @@ -326,7 +340,7 @@ public class HexUtil { * @since 5.7.4 */ public static long hexToLong(String value) { - return Long.parseLong(value, 16); + return Long.parseLong(stripHexPrefix(value), 16); } /** @@ -352,7 +366,7 @@ public class HexUtil { if (null == hexStr) { return null; } - return new BigInteger(hexStr, 16); + return new BigInteger(stripHexPrefix(hexStr), 16); } /** 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 fef023069..b37f4b3ff 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 @@ -3,6 +3,7 @@ package cn.hutool.core.util; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; /** @@ -85,4 +86,34 @@ public class HexUtilTest { final String s1 = HexUtil.decodeHexStr(s); assertEquals("6", s1); } + + @Test + public void hexToIntTest() { + final String hex1 = "FF"; + assertEquals(255, HexUtil.hexToInt(hex1)); + final String hex2 = "0xFF"; + assertEquals(255, HexUtil.hexToInt(hex2)); + final String hex3 = "#FF"; + assertEquals(255, HexUtil.hexToInt(hex3)); + } + + @Test + public void hexToLongTest() { + final String hex1 = "FF"; + assertEquals(255L, HexUtil.hexToLong(hex1)); + final String hex2 = "0xFF"; + assertEquals(255L, HexUtil.hexToLong(hex2)); + final String hex3 = "#FF"; + assertEquals(255L, HexUtil.hexToLong(hex3)); + } + + @Test + public void toBigIntegerTest() { + final String hex1 = "FF"; + assertEquals(new BigInteger("FF", 16), HexUtil.toBigInteger(hex1)); + final String hex2 = "0xFF"; + assertEquals(new BigInteger("FF", 16), HexUtil.toBigInteger(hex2)); + final String hex3 = "#FF"; + assertEquals(new BigInteger("FF", 16), HexUtil.toBigInteger(hex3)); + } }