增强HexUtil自动去除0x#前缀(pr#4163@Github)

This commit is contained in:
Looly 2025-11-26 20:02:12 +08:00
parent ab1774d4e6
commit b8908cf3ef
2 changed files with 26 additions and 19 deletions

View File

@ -12,6 +12,7 @@
* 【core 】 优化`EscapeUtil`兼容不规范的转义pr#4150@Github
* 【core 】 优化`ObjectUtil.contains`String改为CharSequencepr#4154@Github
* 【poi 】 `Word07Writer`增加addText重载支持字体颜色pr#1388@Gitee
* 【core 】 增强`HexUtil`自动去除`0x``#`前缀pr#4163@Github
### 🐞Bug修复
* 【jwt 】 修复verify方法在定义alg为`none`时验证失效问题issue#4105@Github

View File

@ -296,20 +296,6 @@ public class HexUtil {
return Integer.toHexString(value);
}
/**
* 去除十六进制字符串的常见前缀 0x0X#
*
* @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
*
@ -318,7 +304,7 @@ public class HexUtil {
* @since 5.7.4
*/
public static int hexToInt(String value) {
return Integer.parseInt(stripHexPrefix(value), 16);
return Integer.parseInt(removeHexPrefix(value), 16);
}
/**
@ -340,7 +326,7 @@ public class HexUtil {
* @since 5.7.4
*/
public static long hexToLong(String value) {
return Long.parseLong(stripHexPrefix(value), 16);
return Long.parseLong(removeHexPrefix(value), 16);
}
/**
@ -366,7 +352,7 @@ public class HexUtil {
if (null == hexStr) {
return null;
}
return new BigInteger(stripHexPrefix(hexStr), 16);
return new BigInteger(removeHexPrefix(hexStr), 16);
}
/**
@ -406,4 +392,24 @@ public class HexUtil {
return builder.toString();
}
/**
* 去除十六进制字符串的常见前缀 0x0X#
*
* @param hexStr 十六进制字符串
* @return 去除前缀后的字符串
*/
private static String removeHexPrefix(String hexStr) {
if (StrUtil.length(hexStr) > 1) {
final char c0 = hexStr.charAt(0);
switch (c0) {
case '0':
if (hexStr.charAt(1) == 'x' || hexStr.charAt(1) == 'X') {
return hexStr.substring(2);
}
case '#':
return hexStr.substring(1);
}
}
return hexStr;
}
}